c++ parse int from string(c ++从字符串中解析int)
问题描述
可能重复:
如何在 C++ 中将字符串解析为 int?
我做了一些研究,有些人说要使用 atio,有些人说它不好,反正我无法让它工作.
I have done some research and some people say to use atio and others say it's bad, and I can't get it to work anyways.
所以我只想问清楚,将字符串转换为 int 的正确方法是什么.
So I just want to ask flat out, whats the right way to convert a string to a int.
string s = "10";
int i = s....?
谢谢!
推荐答案
在 C++11 中,使用
std::stoi
为:std::string s = "10"; int i = std::stoi(s);
请注意,如果无法执行转换,
std::stoi
将抛出std::invalid_argument
类型的异常,或者std::out_of_range
> 如果转换导致溢出(即字符串值对于int
类型来说太大).您可以使用std::stol
或std:stoll
虽然以防万一int
对于输入字符串来说似乎太小了.Note that
std::stoi
will throw exception of typestd::invalid_argument
if the conversion cannot be performed, orstd::out_of_range
if the conversion results in overflow(i.e when the string value is too big forint
type). You can usestd::stol
orstd:stoll
though in caseint
seems too small for the input string.在 C++03/98 中,可以使用以下任何一种:
In C++03/98, any of the following can be used:
std::string s = "10"; int i; //approach one std::istringstream(s) >> i; //i is 10 after this //approach two sscanf(s.c_str(), "%d", &i); //i is 10 after this
请注意,对于输入 s = 10jh"
,上述两种方法都会失败.他们将返回 10 而不是通知错误.因此,安全可靠的方法是编写自己的函数来解析输入字符串,并验证每个字符以检查它是否为数字,然后相应地工作.这是一个强大的实现(虽然未经测试):
Note that the above two approaches would fail for input s = "10jh"
. They will return 10 instead of notifying error. So the safe and robust approach is to write your own function that parses the input string, and verify each character to check if it is digit or not, and then work accordingly. Here is one robust implemtation (untested though):
int to_int(char const *s)
{
if ( s == NULL || *s == ' ' )
throw std::invalid_argument("null or empty string argument");
bool negate = (s[0] == '-');
if ( *s == '+' || *s == '-' )
++s;
if ( *s == ' ')
throw std::invalid_argument("sign character only.");
int result = 0;
while(*s)
{
if ( *s < '0' || *s > '9' )
throw std::invalid_argument("invalid input string");
result = result * 10 - (*s - '0'); //assume negative number
++s;
}
return negate ? result : -result; //-result is positive!
}
此解决方案是我的另一个解决方案的略微修改版本.
This solution is slightly modified version of my another solution.
这篇关于c ++从字符串中解析int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c ++从字符串中解析int
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 从python回调到c++的选项 2022-11-16