Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

String with integers?

0 views
Skip to first unread message

mlt

unread,
Mar 31, 2009, 4:50:22 PM3/31/09
to
In java an int can be included in a string like:

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++?


Wojciech Pietruszewski

unread,
Mar 31, 2009, 5:10:33 PM3/31/09
to
String in c++ is string, you can parse such string to get the integer.

"mlt" <as...@asd.com> wrote in message
news:49d2821d$0$90267$1472...@news.sunsite.dk...

mlt

unread,
Mar 31, 2009, 5:15:15 PM3/31/09
to
Ok so its not possible to convert an integer to a string without writing a
small function?


"Wojciech Pietruszewski" <wpietru...@gmail.com> wrote in message
news:gqu105$mba$1...@atlantis.news.neostrada.pl...

Jeff Schwab

unread,
Mar 31, 2009, 5:21:43 PM3/31/09
to

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);

wp8088

unread,
Mar 31, 2009, 5:22:13 PM3/31/09
to
The easiest way would use the std::atoi

Victor Bazarov

unread,
Mar 31, 2009, 5:47:44 PM3/31/09
to
wp8088 wrote:
> The easiest way would use the std::atoi

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

wp8088

unread,
Mar 31, 2009, 5:56:33 PM3/31/09
to
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi.html

#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...

Alf P. Steinbach

unread,
Mar 31, 2009, 6:06:09 PM3/31/09
to
* mlt:

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!

mlt

unread,
Mar 31, 2009, 6:19:35 PM3/31/09
to
Well I was more looking for int to string and not the other way around.


"wp8088" <wpietru...@gmail.com> wrote in message
news:gqu3me$s7j$1...@atlantis.news.neostrada.pl...

peter koch

unread,
Mar 31, 2009, 6:30:17 PM3/31/09
to

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

Vladyslav Lazarenko

unread,
Mar 31, 2009, 7:26:47 PM3/31/09
to
Guys,

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);

wp8088

unread,
Apr 1, 2009, 2:58:32 AM4/1/09
to
fair enough there you are

#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...

Jorgen Grahn

unread,
Apr 1, 2009, 3:15:24 AM4/1/09
to

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!

James Kanze

unread,
Apr 1, 2009, 4:15:04 AM4/1/09
to
On Mar 31, 10:50 pm, "mlt" <a...@asd.com> wrote:
> In java an int can be included in a string like:

> 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

James Kanze

unread,
Apr 1, 2009, 4:20:48 AM4/1/09
to
On Apr 1, 1:26 am, Vladyslav Lazarenko <vlazare...@volanttrading.com>
wrote:

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() ) ;

Alf P. Steinbach

unread,
Apr 1, 2009, 4:24:28 AM4/1/09
to
* James Kanze:

> On Mar 31, 10:50 pm, "mlt" <a...@asd.com> wrote:
>> In java an int can be included in a string like:
>
>> 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.)

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,

Jorgen Grahn

unread,
Apr 1, 2009, 2:00:30 PM4/1/09
to
On Wed, 01 Apr 2009 10:24:28 +0200, Alf P. Steinbach <al...@start.no> wrote:
> * 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.

> 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.

Alf P. Steinbach

unread,
Apr 1, 2009, 2:34:42 PM4/1/09
to
* Jorgen Grahn:

> On Wed, 01 Apr 2009 10:24:28 +0200, Alf P. Steinbach <al...@start.no> wrote:
>> * 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.

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

unread,
Apr 1, 2009, 4:24:10 PM4/1/09
to
On Apr 1, 8:00 pm, Jorgen Grahn <grahn+n...@snipabacken.se> wrote:
> On Wed, 01 Apr 2009 10:24:28 +0200, Alf P. Steinbach <al...@start.no> wrote:

> > * 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.

Jorgen Grahn

unread,
Apr 3, 2009, 8:57:49 AM4/3/09
to
On Wed, 01 Apr 2009 20:34:42 +0200, Alf P. Steinbach <al...@start.no> wrote:
> * Jorgen Grahn:
...

>> I find that with integers, I usually have to specify the width, for
>> alignment in tables.
...

> 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.

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

unread,
Apr 5, 2009, 3:51:53 PM4/5/09
to
look up itoa then :-)


--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

James Kanze

unread,
Apr 6, 2009, 4:34:29 AM4/6/09
to
On Apr 5, 9:51 pm, Daniel Pitts
<newsgroup.spamfil...@virtualinfinity.net> wrote:

> 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.)

rishabh

unread,
Apr 6, 2009, 5:23:04 AM4/6/09
to

The best thing you can do is use following code instead:

std::string str = "test";

char temp[100];
str += itoa(222, temp, 10);

Beej Jorgensen

unread,
Apr 6, 2009, 5:42:27 AM4/6/09
to
James Kanze <james...@gmail.com> wrote:
><newsgroup.spamfil...@virtualinfinity.net> wrote:
>> look up itoa then :-)
>
>Look it up where?

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.)

Daniel Pitts

unread,
Apr 6, 2009, 10:30:04 AM4/6/09
to
James Kanze wrote:
> On Apr 5, 9:51 pm, Daniel Pitts
> <newsgroup.spamfil...@virtualinfinity.net> wrote:
>
>> 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.)

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.

peter koch

unread,
Apr 6, 2009, 4:03:16 PM4/6/09
to
On 6 Apr., 16:30, Daniel Pitts

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

James Kanze

unread,
Apr 7, 2009, 3:58:13 AM4/7/09
to
On Apr 6, 11:42 am, Beej Jorgensen <b...@beej.us> wrote:
> 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.

> 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.

James Kanze

unread,
Apr 7, 2009, 4:05:16 AM4/7/09
to

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.)

peter koch

unread,
Apr 7, 2009, 5:44:43 AM4/7/09
to
On 7 Apr., 09:58, James Kanze <james.ka...@gmail.com> wrote:
> On Apr 6, 11:42 am, Beej Jorgensen <b...@beej.us> wrote:
>
> > 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.

>
> >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.


>
> > 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

unread,
Apr 8, 2009, 3:57:11 AM4/8/09
to
On Apr 7, 11:44 am, peter koch <peter.koch.lar...@gmail.com> wrote:
> On 7 Apr., 09:58, James Kanze <james.ka...@gmail.com> wrote:>
> On Apr 6, 11:42 am, Beej Jorgensen <b...@beej.us> wrote:

> > > 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.

0 new messages