#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string str = "10";
int num = 0;
//方法一:通过C函数atoi
num = atoi(str.c_str());
cout << num << endl;
//方法二:通过C++ 11 函数stoi
str = "20";
num = stoi(str);
cout << num << endl;
//方法三:使用istringstream
str = "30";
istringstream is(str);
is >> num;
cout << num << endl;
//方法四:通过C函数strol
str = "40";
int number = strtol(str.c_str(), nullptr, 10);
cout << number << endl;
//方法五:使用c函数 sscanf_s
str = "50";
sscanf_s(str.c_str(), "%d",&num);
cout << num << endl;
return 0;
}
C++ string转int的五种方法
于 2024-05-21 17:30:15 首次发布