如何在 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