String str = ""+33 + "strings";
In c++ I have only found:
std::string str = "test";
std::stringstream out;
out << 222;
str = str + out.str();
Is that really the only way to do this in C++?
"mlt" <as...@asd.com> wrote in message
news:49d2821d$0$90267$1472...@news.sunsite.dk...
"Wojciech Pietruszewski" <wpietru...@gmail.com> wrote in message
news:gqu105$mba$1...@atlantis.news.neostrada.pl...
No, there are plenty of different ways. One way that boils down to what
you've written is Boost.Lexical Cast:
std::string str( "test" );
str += boost::lexical_cast<std::string>(33);
What's that?
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
string str="2";
int i;
i=atoi(str.c_str());
i=i+2;
cout<<i<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
"Victor Bazarov" <v.Aba...@comAcast.net> wrote in message
news:gqu320$3bl$1...@news.datemas.de...
No, there are umpteen ways, but the core language and standard library does not
support the simple Java syntax.
In C++ you decide what libraries to use, or you create the functionality.
E.g., check out boost::lexical_cast, from the Boost library.
Or if installing Boost sounds daunting (note: you don't have to build anything
to use simple functionality like lexical_cast), you can create such
functionality yourself by -- yes -- writing appropriate small routines
and/or classes.
And that is probably best, because for reasons of efficiency you really
shouldn't use string value concatenation as the default. For almost no matter
the language it leads easily to O(n^2) behavior in loops, that is, time that
increases as the square of the number of items, which goes slow very fast. :)
Instead preferentially concatenate on to the end of a string variable, like
<code>
#include <iostream>
#include <string>
#include <sstream>
//--------------------------------- Machinery:
std::string stringFrom( int x )
{
std::ostringstream stream;
stream << x;
return stream.str();
}
class S
{
private:
std::string myString;
public:
operator std::string& () { return myString; }
operator std::string const& () const { return myString; }
};
std::string& operator<<( std::string& s, char const rhs[] )
{
return s.append( rhs );
}
std::string& operator<<( std::string& s, int rhs )
{
return s.append( stringFrom( rhs ) );
}
//--------------------------------- Example usage:
void foo( std::string const& s )
{
std::cout << s << std::endl;
}
int main()
{
// Java: foo( "Level " + 42 + "." )
foo( S() << "Level " << 42 << "." );
}
</code>
For reuse, add "inline" to each routine definition and place the machinery in a
header file, which you can then just #include.
Hrmf, this should really be a FAQ.
Cheers & hth.,
- Alf
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!
"wp8088" <wpietru...@gmail.com> wrote in message
news:gqu3me$s7j$1...@atlantis.news.neostrada.pl...
Yes. And that is IMHO the correct way to do it. The stringstream is
the flexible approach and also the typesafe way to do stuff. Do you
really want to have string + <anything> work regardless of the type of
<anything>? On reflection, I believe not.
/Peter
It looks like we forgot about Boost.Format. Example:
int i = 1986;
const char s[] = "STR";
std::string res = boost::str(boost::format("This is my number: %1%.
This is my string: %2%") % i % s);
#include <cstdlib>
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
int i = 42;
ostringstream ss;
ss << i;
string str = ss.str();
system("PAUSE");
return EXIT_SUCCESS;
}
"mlt" <as...@asd.com> wrote in message
news:49d2821d$0$90267$1472...@news.sunsite.dk...
It looks better when you rewrite it without operator+ :
std::stringstream out;
out << "test" << 222;
// use out.str();
You might also find that what you really want to do with the string is
to place it on a stream, so you can skip the intermediate string.
/Jorgen
--
// Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.se> R'lyeh wgah'nagl fhtagn!
> String str = ""+33 + "strings";
Which is a nice source of errors, and a serious design flaw.
> In c++ I have only found:
> std::string str = "test";
> std::stringstream out;
> out << 222;
> str = str + out.str();
> Is that really the only way to do this in C++?
Yep. Strings are not formatters; formatting is done by
ostream. In Java, of course, if you want to do it right,
and avoid confusion and maintenance problems, you use
java.text.Format. (The basic problem, of course, is that
there are many valid conversions of an int to a string. In
anything but toy programs, you generally have to specify
some of the details.)
--
James Kanze (GABI Software) email:james...@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
The problem is that the use of '%' as both the operator and
the format specifier very quickly leads to unreadable
expressions (not to mention the fact that the precedence of
% is wrong). The standard library's choice of << here is
about the best you can do if you insist on an operator; a
better solution would be to use a named function, or even an
operator(), e.g.:
std::string res( Format(
"This is my number: %1%. This is my string: %2%" )
.with( i )
.with( s )
.str() ) ;
No, the difference between general formatting with zillions of options, and
default simple conversion of an integer to string, is just that, zillions of
options versus default simple.
In some cases you (or perhaps not "you" you, but the generic you) want one, in
other cases the other.
Whether the program is toy or the next Photoshop has nothing to do with it; in
both kinds of program the default simple conversion is the one most often
required, and the zillions-of-options one the one least often required.
And formatting isn't necessarily done by ostream.
The nice thing about C++ is that we can choose, and many choose to not use
iostreams except for -- heh, toy programs. ;-)
Cheers,
I find that with integers, I usually have to specify the width, for
alignment in tables. Often hex too, although I guess most other
applications do not print a lot of hex. With float and double, I
think you almost *always* want to specify the precision, so you do not
mislead your users by printing lots of digits which are deep within
the numerical error.
> The nice thing about C++ is that we can choose, and many choose to not use
> iostreams except for -- heh, toy programs. ;-)
With other peoples' classes, you have no choice. If they can be
printed at all, it's by placing them on an ostream. There is no other
universally accepted way.
Well, that's also the case for strings. And when you can do that for strings,
then why should that functionality be duplicated for the conversion of integer
to string? That redundant functionality just adds complexity and (when it's
used) makes it harder to do simple things like aligning headers in columns, and
collides directly with the principle of separation of concerns.
And speaking of separation of concerns, if you need a tabular presentation, why
try to shoehorn also that into conversion integer -> string.
Why not, regarding that presentation issue, generate just a CSV file/stream of
data, or XML, whatever pure data format (one concern, data) and run it through a
filter generating e.g. XHTML (second concern, presentation)? It's simpler. And
it's far more flexible. And it allows you to avoid loss of precision. And it's
better for compatibility with other programs and future versions of current one.
> Often hex too, although I guess most other
> applications do not print a lot of hex. With float and double, I
> think you almost *always* want to specify the precision, so you do not
> mislead your users by printing lots of digits which are deep within
> the numerical error.
Yah.
>> The nice thing about C++ is that we can choose, and many choose to not use
>> iostreams except for -- heh, toy programs. ;-)
>
> With other peoples' classes, you have no choice. If they can be
> printed at all, it's by placing them on an ostream. There is no other
> universally accepted way.
Huh.
The PC I'm writing this on is chock full of classes whose objects can generate
textual representations of themselves in various ways, and so it is on every
Windows PC; there are thousands of classes. Some of them are COM classes, others
are .NET classes. I've yet to see any of them printing to C++ std::ostream.
So there. :)
Not that I necessarily recommend either technology mentioned above for any given
purpose.
It's just that, by simple inspection of nearest computer, your "universally
accepted way" seems to actually be very much far less than universally accepted.
Cheers & hth.,
> > * James Kanze:
> ...
> >> (The basic problem, of course, is that there are many valid
> >> conversions of an int to a string. In anything but toy
> >> programs, you generally have to specify some of the
> >> details.)
> ...
> > Whether the program is toy or the next Photoshop has nothing
> > to do with it; in both kinds of program the default simple
> > conversion is the one most often required, and the
> > zillions-of-options one the one least often required.
> I find that with integers, I usually have to specify the
> width, for alignment in tables. Often hex too, although I
> guess most other applications do not print a lot of hex. With
> float and double, I think you almost *always* want to specify
> the precision, so you do not mislead your users by printing
> lots of digits which are deep within the numerical error.
Alf's actually at least partially right with regards to
integers. There is a more or less reasonable default, which is
sufficient for debugging and trace outputs, at least. This
doesn't extend to other types, however, and even with integers,
you'll often want something other than the default.
> > The nice thing about C++ is that we can choose, and many
> > choose to not use iostreams except for -- heh, toy
> > programs. ;-)
What else is there to choose from? <cstdio> is a design
disaster. The original iostream was actually pretty good, and
could even serve as a model solution for some design problems.
(Note the different techniques used to allow extension, e.g. to
support user defined types, or to support user defined sinks and
sources.) I don't think there's any way the changes made by the
standards committee can be considered an improvement, but at
least, you can ignore them most of the time.
> With other peoples' classes, you have no choice. If they can
> be printed at all, it's by placing them on an ostream. There
> is no other universally accepted way.
Well, boost::format (or my older GB_Format) could handle them.
In both cases, of course, because they're just wrappers around
ostream.
I feel about XML as you feel about iostreams ...
More often than not, my programs generate output in some homegrown but
documented text file format, e.g. lines of name-whitespace-value. Then
it's polite to human readers to align columns so they can eyeball the
data.
But yes, when I sometimes generate HTML or tbl(1) tables, I do not
have to use any padding mechanisms.
...
>>> The nice thing about C++ is that we can choose, and many choose to not use
>>> iostreams except for -- heh, toy programs. ;-)
>>
>> With other peoples' classes, you have no choice. If they can be
>> printed at all, it's by placing them on an ostream. There is no other
>> universally accepted way.
>
> Huh.
>
> The PC I'm writing this on is chock full of classes whose objects can generate
> textual representations of themselves in various ways, and so it is on every
> Windows PC; there are thousands of classes. Some of them are COM classes, others
> are .NET classes. I've yet to see any of them printing to C++ std::ostream.
OK, but I meant "no other universally accepted way /within standard C++/".
(Although I suspect there are heretics^Wsub-cultures who use toString()
methods.)
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
> look up itoa then :-)
Look it up where? It's not part of standard C++. It's not
defined by Posix. It's not present in the man pages on my
machines (Solaris and Linux). It sounds like something very
implementation specific; whatever it is, it's certainly not
portable. (I do seem to remember it being present in some older
Unix---AT&T's version 7, or something like that. But I doubt
many people are running that.)
The best thing you can do is use following code instead:
std::string str = "test";
char temp[100];
str += itoa(222, temp, 10);
These days? Wikipedia. :)
http://en.wikipedia.org/wiki/Itoa
There's even an awesome link to some ancient man pages there.
-Beej
(Nothing in this post is intended to contradict anything in your post.)
Indeed, my mistake. Its been so long since I've had to worry about
low-level string manipulation that I didn't realize itoa was a
non-standard extension.
stringstream seems like the way to go then.
I believe that for convenience, there is no alternative to
stringstream. But I am surprised that anyone suggested atoi as the
primary function when we all (should) know that strtol is the C-way to
go.
/Peter
> ><newsgroup.spamfil...@virtualinfinity.net> wrote:
> >> look up itoa then :-)
> >Look it up where?
> These days? Wikipedia. :)
That is NOT the place to look up a standard function. One of
the established standards or an established reference work would
be preferable, if you're interested in portability. Otherwise,
the documentation for your compiler.
> http://en.wikipedia.org/wiki/Itoa
Which, when carefully read, does say that 1) the function isn't
standard, and can't be used portably, and 2) presents a number
of different signatures which it has had in older systems, so
even if you've got it, you have to first find out which version
you've got.
> There's even an awesome link to some ancient man pages there.
I've got a copy of the version 7 Unix manuals on my machine
somewhere, too. I don't use them to find out about the state
of things today. What's more significant in the Wikipedia
article is what's missing: any links to a modern specification.
Which beggers the question, since you then have to write itoa.
(Back in the old days, there was a function under Unix by this
name, but it's not part of the standard, and not supported by
most compilers or systems.)
And you did not have to read very carefully. I found the description
there quite accurate and easy to read.
>
> > There's even an awesome link to some ancient man pages there.
>
> I've got a copy of the version 7 Unix manuals on my machine
> somewhere, too. I don't use them to find out about the state
> of things today. What's more significant in the Wikipedia
> article is what's missing: any links to a modern specification.
But they do link to opengroup.org for strtol, and the skim of that
documentation looked quite good. Just for the fun of it, it also
looked up std::vector amd I believe the documentation there also was
fine, even if I would not use it as a reference. For a tutorial it was
great although I found the illustrations to push_back and pop_back a
little confusing. The linkswere to places I did not know - and to sgi
which is not to good, but there were references to the C++ standard
which is good.
All in all wikipedia did well here.
/Peter
> > > James Kanze <james.ka...@gmail.com> wrote:
> > > ><newsgroup.spamfil...@virtualinfinity.net> wrote:
> > > >> look up itoa then :-)
> > > >Look it up where?
> > > These days? Wikipedia. :)
> > That is NOT the place to look up a standard function. One
> > of the established standards or an established reference
> > work would be preferable, if you're interested in
> > portability. Otherwise, the documentation for your
> > compiler.
> I never use wikipedia look up C++ questions, but I do use the
> internet quite often. And I often use Wikipedia if there is
> other stuff I want to check out.
I love the Wikipedia, and use it for a lot of things. But not
as a definitive reference work, for anything.
As for looking up the information on the Internet...
Regretfully, there are a lot of bad sites out there. Unless you
have some means of judging the quality or the authority of the
site, you have to be careful. (With some experience, of course,
you can often learn to recognize which sites are "authorities",
the Open Unix Standard for Unix, for example. Regretfully, I
don't think there is one for C++.)
> > >http://en.wikipedia.org/wiki/Itoa
> > Which, when carefully read, does say that 1) the function isn't
> > standard, and can't be used portably, and 2) presents a number
> > of different signatures which it has had in older systems, so
> > even if you've got it, you have to first find out which version
> > you've got.
> And you did not have to read very carefully. I found the
> description there quite accurate and easy to read.
Yes, I read it carefully. While there's certainly nothing false
in it, I found the introduction somewhat misleading:
"widespread", "often provided", etc. Still, it's a lot better
than a few others I've seen.
> > > There's even an awesome link to some ancient man pages
> > > there.
> > I've got a copy of the version 7 Unix manuals on my machine
> > somewhere, too. I don't use them to find out about the state
> > of things today. What's more significant in the Wikipedia
> > article is what's missing: any links to a modern specification.
> But they do link to opengroup.org for strtol, and the skim of
> that documentation looked quite good.
Yes. My criticism here wasn't so much one of the Wikipedia
page, but of 1) it being cited as a reference for the function
(even though the page itself says that the function cannot be
used in portable code), and 2) the reference to "an awesome
link", which isn't relevant to the current question.
> Just for the fun of it, it also looked up std::vector amd I
> believe the documentation there also was fine, even if I would
> not use it as a reference.
Because that's not its role. Especially not in such cases,
where accessible definite references (the original sources)
exist. I'm not criticizing Wikipedia, just the way it's being
used.
> For a tutorial it was great although I found the illustrations
> to push_back and pop_back a little confusing. The linkswere to
> places I did not know - and to sgi which is not to good, but
> there were references to the C++ standard which is good.
> All in all wikipedia did well here.
It usually does. The only real problems are that it's not
always obvious when it doesn't, and that too many people are
trying to use it for something it isn't: an original source or a
definitive reference. It's probably not a good tutorial,
either---if you want to learn the STL, I'd recommend a book
(Matt Austern or Niko Josuttis), for example, rather than the
Wikipedia.