
课程咨询: 400-996-5531 / 投诉建议: 400-111-8989
认真做教育 专心促就业
一、string 转 int
1、atoi
string s = "-1234";
cout <<"atoi(s.c_str()): " << atoi(s.c_str()) << endl;
cout << typeid(atoi(s.c_str())).name() << endl;
2、strtol
ong int strtol (const charstr, char* endptr, int base);
str 为要转换的字符串,endstr 为第一个不能转换的字符的指针,base 为字符串 str 所采用的进制。
int x = 0;
string str1 = "100";
string str2 = "-100";
string str3 = "100a";
x = strtol(str1.c_str(), nullptr, 10);
cout << x << endl;
x = strtol(str2.c_str(), nullptr, 10);
cout << x << endl;
x = strtol(str3.c_str(), nullptr, 10);
cout << x << endl;
3、stoi c++11之后才引入,需要引入 <string> 头文件
int x = 0;
string str1 = "100";
string str2 = "-100";
string str3 = "100a";
x = stoi(str1);
cout << x << endl;
x = stoi(str2);
cout << x << endl;
x = stoi(str3);
cout << x << endl;
4、stringstream 需要引入<sstream> 头文件
int stringToInt(const string& s)
{
stringstream ss;
int result;
ss << s;
ss >> result;
return result;
}
int main()
{
string str1 = "100";
string str2 = "-100";
string str3 = "100a";
cout << stringToInt(str1) << endl;
cout << stringToInt(str2) << endl;
cout << stringToInt(str3) << endl;
}
二、int 转 string
1、sprintf_s
int number = 100;
char buff[128] = { 0 };
sprintf_s(buff, 128, "%d", number);
cout << buff << endl;
2、stringstream
需引入该<stringstream>头文件
int number = 100;
stringstream ss;
ss << number;
string str = ss.str();
cout << str << endl;
3、to_string()
c++11 后的新特性,需要引入<string> 头文件
int number = 100;
string str = to_string(number);
cout << str << endl;