如何將字串解析為 C++ 中的 int?


你可以使用 string 流來解析 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


更新於:2020 年 2 月 12 日

1K+ 瀏覽量

開啟你的事業

完成課程認證

開始學習
廣告