c++如何将string转化int的⽅法⽬录
⽅法1
在C标准库⾥⾯,使⽤atoi(表⽰ ascii to integer)是把字符串转换成整型数的⼀个函数int atoi(const char *nptr)⽅法2
c++中string的用法在C++标准库⾥⾯,使⽤stringstream:(stringstream可以⽤于各种数据类型之间的转换)。
例⼦:
#include <sstream>
#include <string>
std::string text = "152";
int number;
std::stringstream ss;
ss << text;//可以是其他数据类型
ss >> number; //string -> int
⽅法3
int stoi (const string& str, size_t* idx = 0, int base = 10);
Parses str interpreting its content as an integral number of the specified base,
which is returned as an int value.If idx is not a null pointer,
the function also sets the value of idx to the position of the first character
in str after the number.
题外话
反问,在C++中,如何将数值类型转换为string类型呢?
std::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);
Convert numerical value to string,Returns a string with the representation
of val.