From int to std::string

The sprintf() function is the standard approach for converting an integer to a c-string - being the well known itoa() function not part of any C standard.

For C++ std::string it is usually preferred going through a std::stringstream and then costructing our string out if it.

In this example we see how to create a few strings from ints, and printing them using the dump() function described previously:

std::vector<std::string> vs;
vs.reserve(10);

std::stringstream ss;
for(int i = 0; i < 10; ++i)
{
ss << i; // 1.
std::string s(ss.str()); // 2.
vs.push_back(s);
ss.str(""); // 3.
}
dump(vs);

1. Inside the loop we put an integer in the string stream;
2. then we extract the string from the stream, use it to create a new string by copy, and finally push the newly created string in the vector;
3. we reset the stream, to be ready for a new string creation.

No comments:

Post a Comment