如何在 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(string 到 int)、stol(string 到 long)、stoll(string 到 long long)、stoul(string 到 unsigned long)等。
示例
可以使用这些功能如下 -
#include<iostream>
using namespace std;
int main() {
string s = "12345";
int x = stoi(s);
cout << x;
}输出
这将给出了输出 -
12345
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP