#include <sstream> //include this to use string streams
#include <string>
int main()
{
int number = 1234;
std::ostringstream ostr; //output string stream
ostr << number; //use the string stream just like cout,
//except the stream prints not to stdout but to a string.
std::string theNumberString = ostr.str(); //the str() function of the stream
//returns the string.
//now theNumberString is "1234"
}
请注意,您还可以使用字符串流将浮点数转换为字符串,还可以像使用 cout一样根据需要格式化字符串
std::ostringstream ostr;
float f = 1.2;
int i = 3;
ostr << f << " + " i << " = " << f + i;
std::string s = ostr.str();
//now s is "1.2 + 3 = 4.2"
使用 增强词法强制转换。如果您不熟悉 ost,那么从一个像 lexical _ cast 这样的小型库开始是一个不错的主意。下载并安装升级及其文档 到这儿来。尽管升级不在 C + + 标准中,但许多升级库最终都得到了标准化,升级被广泛认为是最好的 C + + 库。
词法强制转换使用下面的流,所以基本上这个选项与前一个选项相同,只是不那么冗长。
#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
float f = 1.2;
int i = 42;
std::string sf = boost::lexical_cast<std::string>(f); //sf is "1.2"
std::string si = boost::lexical_cast<std::string>(i); //sf is "42"
}
How to convert a string to a number in C++03
The most lightweight option, inherited from C, is the functions atoi (for integers (alphabetical to integer)) and atof (for floating-point values (alphabetical to float)). These functions take a C-style string as an argument (const char *) and therefore their usage may be considered a not exactly good C++ practice. cplusplus.com has easy-to-understand documentation on both atoi and atof including how they behave in case of bad input. However the link contains an error in that according to the standard if the input number is too large to fit in the target type, the behavior is undefined.
#include <cstdlib> //the standard C library header
#include <string>
int main()
{
std::string si = "12";
std::string sf = "1.2";
int i = atoi(si.c_str()); //the c_str() function "converts"
double f = atof(sf.c_str()); //std::string to const char*
}
Use string streams (this time input string stream, istringstream). Again, istringstream is used just like cin. Again, do not confuse istringstream with istrstream. The latter is deprecated.
#include <sstream>
#include <string>
int main()
{
std::string inputString = "1234 12.3 44";
std::istringstream istr(inputString);
int i1, i2;
float f;
istr >> i1 >> f >> i2;
//i1 is 1234, f is 12.3, i2 is 44
}
#include <boost/lexical_cast.hpp>
#include <string>
int main()
{
std::string sf = "42.2";
std::string si = "42";
float f = boost::lexical_cast<float>(sf); //f is 42.2
int i = boost::lexical_cast<int>(si); //i is 42
}
float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);
int stoi(const string& str, size_t *idx = 0, int base = 10);
long stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);
long long stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);