How to: Add a number as numeral to std::string
I''d like a clean way of adding any of the default basic types to a string. (everything from signed long, float, char, int etc, etc).
Right now I have an ugly system where I ''add'' each one to a stringstream then copy the string stream back to a string.
There has to be a better way!
Chris Brodie
The way to do it using STL is pretty ugly too.
You need a strstream, which acts like a string. Add all of your data to it using the overloaded "<<" operator (just like cout). Then after you''re done, if you call str () to return a char *. Unfortunately, this also calls freeze (true) so you have to call freeze (false) afterward.
I never use this because it''s so unseemly, but that''s the "standard" way to do it.
Your only other option is good ole sprintf, but then you have the magic-number-sized char arrays that can always overrun their bounds.
Good luck.
You need a strstream, which acts like a string. Add all of your data to it using the overloaded "<<" operator (just like cout). Then after you''re done, if you call str () to return a char *. Unfortunately, this also calls freeze (true) so you have to call freeze (false) afterward.
I never use this because it''s so unseemly, but that''s the "standard" way to do it.
Your only other option is good ole sprintf, but then you have the magic-number-sized char arrays that can always overrun their bounds.
Good luck.
I usually just use stringstream. There are many methods to get a number to a string.
C ways
itoa(num, c_buffer, max_input);
sprintf(c_buffer, "%d", num);
C++ ways (NOTE: some people will need to use strstreams)
stringstream name;
name << 31232321;
cout << name.str() << endl;
string test(name.str());
int val; name >> val;
cout << val << endl;
C ways
itoa(num, c_buffer, max_input);
sprintf(c_buffer, "%d", num);
C++ ways (NOTE: some people will need to use strstreams)
stringstream name;
name << 31232321;
cout << name.str() << endl;
string test(name.str());
int val; name >> val;
cout << val << endl;
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement