How do I put an int on the end of a C++ string object?

Started by
16 comments, last by Zahlman 18 years, 10 months ago
Hello! This is probably a simple thing. If I declare a string object in C++ like so: std::string filename="data"; and I have an int: int level=1; how do I put level on the end of filename? In certain forms of BASIC it would be a simple thing like this: filename="data" filename=filename+level I want to construct "data1.dat" "data2.dat" etc Thanks!
Advertisement
look into _itoa() or just sprintf(). sprintf(buffer, "%s%d", level, number);
if you are using std::string you can use std::stringstream to convert types for you.
#include <sstream> // basic_ostringstream#include <string>  // basic_string//...std::ostringstream oss;oss << "data" << 1 << ".dat";std::string s = oss.str();//....
Maybe I should use an old C string.

Can you convert an int to an old C style string?

So 1 becomes "1" and you can put the two strings together, like
"1" and "hello" becomes "1hello"
If you wanna use C strings use:
char buffer[WHATEVERSIZE];sprintf(buffer, "data%d.dat", number);
The easiest way is to use boost::lexical_cast:
#include <boost/lexical_cast.hpp>std::string filename="data";filename += lexical_cast<std::string>(1); // convert the int to a string
Quote:Original post by snk_kid
#include <sstream> // basic_ostringstream#include <string>  // basic_string//...std::ostringstream oss;oss << "data" << 1 << ".dat";std::string s = oss.str();//....


Save yourself the debugging time.
Quote:Original post by doho
If you wanna use C strings use:
char buffer[WHATEVERSIZE];sprintf(buffer, "data%d.dat", number);


If your going down that route prefer C99's snprintf, if your using VC it doesn't support C99 fully so you'll have to use _snprintf, use some macro magic to select between the two if you want.

if you want to know the reason why check option 2, actually its worth reading the entire article totally related to this thread [grin]
This suits my needs just fine:

char buffer[WHATEVERSIZE];
sprintf(buffer, "data%d.dat", number);

Still fiddling around with trying to put two old C strings together, eg if I have

char text1[]="hello";
char text2[]=" world";

and I want to put them together to make
"hello world"

What's the simplest way to do that?
Without doing anything messy like convert to string objects?

Can you use <sstream> with old C strings?


This topic is closed to new replies.

Advertisement