One, int to string
1. If the compiler you use is based on the latest C++11 standard, then the string and other type conversion problems become very simple, because the corresponding conversion methods have been encapsulated in:
To_string(val) is defined in the standard library; other types can be converted to string.
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val)
2. Implement the string stream object defined in sstream
ostringstream os; //构造一个输出字符串流,流内容为空
int i = 12;
os << i; //向输出字符串流中输出int整数i的内容
cout << os.str() << endl; //利用字符串流的str函数获取流中的内容
Second, string to int
1. C++11 also defines a set of conversion functions such as stoi(s,p,b), stol(s,p,b), stod(s,p,b), which can be converted into int, long, double respectively etc. in the header file<string>
stoi(s,p,b);stol(s,p,b);stoul(s,p,b);stoll(s,p,b);stoull(s,p,b);return the start of s The value of the substring (a string representing the content of an integer), the return value types are: int, long, unsigned long, long long, unsigned long long. Where b represents the base used for conversion, and the default is 10 (representing decimal). p is the pointer of size_t, which is used to store the subscript of the first non-numeric character in s, p defaults to 0, that is, the function does not return the subscript.
stof(s, p); stod(s, p); stold(s, p); Returns the value of the starting substring of s (representing the content of floating-point numbers), and the returned value types are float, double, long double. The effect of the parameter p is the same as in the integer conversion function.
Anything that does not start with a number will throw a std::invalid_argument exception.
#include <iostream>
#include <string>
int main()
{
std::string a = "a123asd";
int i = std::stoi(a);//std::invalid_argument异常
std::cout << i << std::endl;
getchar();
return 0;
}
2.2. The atoi function in the standard library is used, and there are corresponding standard library functions for other types, such as floating-point atof(), long-type atol(), etc. In the header file<cstdlib>
string s = "12";
int a = atoi(s.c_str());
3. Use the string stream object defined in the sstream header file to implement the conversion
istringstream is("12"); //构造输入字符串流,流的内容初始化为“12”的字符串
int i;
is >> i; //从is流中读入一个int整数存入i中