这篇文章将讨论如何在 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 的全部内容。