如何在C ++中将字符串解析为int?
您可以使用字符串流将c++中的int解析为int。您需要在此方法中进行一些错误检查。
示例
#include<iostream>
#include<sstream>
using namespace std;
int str_to_int(const string &str) {
stringstream ss(str);
int num;
ss >> num;
return num;
}
int main() {
string s = "12345";
int x = str_to_int(s);
cout << x;
}输出结果
这将给出输出-
12345
在新的C++11中,有针对此的函数:stoi(字符串到int),stol(字符串到long),stoll(字符串到longlong),stoul(字符串到unsignedlong)等。
示例
您可以如下使用这些功能-
#include<iostream>
using namespace std;
int main() {
string s = "12345";
int x = stoi(s);
cout << x;
}输出结果
这将给出输出-
12345