我听说我应该使用 strtol
而不是 atoi
因为它更好的错误处理。我想通过查看是否可以使用此代码来检查字符串是否为整数来测试 strtol
:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
string testString = "ANYTHING";
cout << "testString = " << testString << endl;
int testInt = strtol(testString.c_str(),NULL,0);
cout << "errno = " << errno << endl;
if (errno > 0)
{
cout << "There was an error." << endl;
cout << "testInt = " << testInt << endl;
}
else
{
cout << "Success." << endl;
cout << "testInt = " << testInt << endl;
}
return 0;
}
我用 5
替换了 ANYTHING
并且它完美地工作:
testString = 5
errno = 0
Success.
testInt = 5
当我使用 2147483648
时,最大可能的 int
+ 1 (2147483648),它返回这个:
testString = 2147483648
errno = 34
There was an error.
testInt = 2147483647
很公平。但是,当我尝试使用 Hello world!
时,它错误地认为它是一个有效的 int
并返回 0
:
testString = Hello world!
errno = 0
Success.
testInt = 0
注意事项:
- 我在 Windows 上使用 Code::Blocks 和 GNU GCC 编译器
- 在“Compiler Flags”中勾选“Have g++ follow the C++11 ISO C++ language standard [-std=c++11]”。
最佳答案
根据the man page of strtol
.您必须定义您的功能,例如:
bool isNumeric(const std::string& str) {
char *end;
long val = std::strtol(str.c_str(), &end, 10);
if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 && val == 0)) {
// if the converted value would fall out of the range of the result type.
return false;
}
if (end == str) {
// No digits were found.
return false;
}
// check if the string was fully processed.
return *end == '\0';
}
在C++11中,我更喜欢使用std::stol
而不是std::strtol
,例如:
bool isNumeric(const std::string& str) {
try {
size_t sz;
std::stol(str, &sz);
return sz == str.size();
} catch (const std::invalid_argument&) {
// if no conversion could be performed.
return false;
} catch (const std::out_of_range&) {
// if the converted value would fall out of the range of the result type.
return false;
}
}
std::stol
调用 std::strtol
,但您直接使用 std::string
并简化了代码。
关于C++:使用 "strtol"检查字符串是否为有效整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37956474/