Hvis det er en C++ streng (ie. std::string), må man omvejen omkring en stringstream:
#include <sstream>
#include <iostream>
#include <string>
int main()
{
int i = 123;
std::ostringstream os;
std::string s;
std::stringstream is;
// Convert int to ostringstream
os << i;
// Then from ostringstream to string
s = os.str();
std::cout << "Som string " << s << std::endl;
std::cout << "Som int " << i << std::endl;
s = "321";
// From string to stringstream
is << s;
// From stringstream to int
is >> i;
std::cout << "Som string " << s << std::endl;
std::cout << "Som int " << i << std::endl;
return 0;
}
man kan dog godt bruge:
int i = strtol(s.c_str(), 0, 0);
Men man kan ikke bruge sprintf, den anden vej.