這篇文章將討論如何在 C++ 中將字符串轉換為 int。
1.使用 std::stoi
功能
標準方法是使用 std::stoi
用於將字符串轉換為整數的函數。這 stoi
函數在 C++11 中引入並在頭文件中定義 <string>
.它拋出 std::invalid_argument
或者 std::out_of_range
錯誤輸入或整數溢出的異常。值得注意的是,它會將字符串轉換為 10xyz
為整數 10
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <string> int main() { std::string s = "10"; try { int i = std::stoi(s); std::cout << i << std::endl; } catch (std::invalid_argument const &e) { std::cout << "Bad input: std::invalid_argument thrown" << std::endl; } catch (std::out_of_range const &e) { std::cout << "Integer overflow: std::out_of_range thrown" << std::endl; } return 0; } |
2.使用字符串流
std::stringstream
可用於轉換 std::string
到其他數據類型,反之亦然。這遇到了同樣的問題 std::stoi
確實,即,它將轉換字符串,例如 10xyz
為整數 10
.它返回 INT_MAX
或者 INT_MIN
如果轉換後的值超出整數數據類型的範圍。如果字符串的值不能表示為 int,則返回 0。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <string> #include <sstream> int main() { std::string s = "10"; int i; std::istringstream(s) >> i; std::cout << i << std::endl; return 0; } |
3.使用 boost::lexical_cast
另一個不錯的選擇是使用 boost::lexical_cast.它拋出 boost::bad_lexical_cast
無法構造有效整數或發生溢出時的異常。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <boost/lexical_cast.hpp> #include <string> int main() { std::string s = "10"; int i; try { i = boost::lexical_cast<int>(s); std::cout << i << std::endl; } catch (boost::bad_lexical_cast const &e) { //錯誤的輸入 std::cout << "error" << std::endl; } return 0; } |
4.使用 std::atoi
功能
我們也可以使用 std::atoi
將字符串轉換為 int 的函數。它需要一個 C 字符串作為參數,因此我們需要將我們的字符串轉換為 C 字符串。我們可以使用 std::string::c_str
.
請注意,如果轉換後的值超出整數數據類型的範圍,則其行為未定義。如果字符串的值不能表示為 int,則返回 0。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> #include <cstdlib> int main() { std::string s = "10"; int i = std::atoi(s.c_str()); std::cout << i << std::endl; return 0; } |
5.使用 sscanf()
功能
我們可以將 C 字符串傳遞給 sscanf()
函數作為參數,並將其轉換為格式說明符中指定的相應數據類型。它將返回成功時的參數總數和失敗時的 EOF。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <cstdio> #include <string> int main() { std::string s = "10"; int i; if (sscanf(s.c_str(), "%d", &i) == 1) { std::cout << i << std::endl; } else { std::cout << "Bad Input"; } return 0; } |
6.使用基於範圍的for循環
最後,天真的解決方案是實現我們自己的例程。這個想法是使用基於範圍的 for 循環 (C++11) 遍歷字符串的字符並單獨處理每個數字。如果轉換後的值超出整數數據類型的範圍,則行為未定義。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <string> int main() { std::string s = "10"; int i = 0; for (char c: s) { if (c >= '0' && c <= '9') { i = i * 10 + (c - '0'); } else { std::cout << "Bad Input"; return 1; } } std::cout << i << std::endl; return 0; } |
這就是在 C++ 中將字符串轉換為 int 的全部內容。