如何在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
热门推荐
10 感谢韩语老师祝福语简短
11 升职文案高级祝福语简短
12 花童结婚祝福语大全简短
13 向国庆送祝福语简短
14 什么寄语简短祝福语女生
15 客户回礼祝福语大全简短
16 女孩生日祝福语简短创意
17 家长回复节日祝福语简短
18 给外婆敬酒祝福语简短