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.
相关文章