如何在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 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短