【发布时间】:2016-10-23 17:07:05
【问题描述】:
我听说我应该使用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 编译器
- 在“编译器标志”中选中“让 g++ 遵循 C++11 ISO C++ 语言标准 [-std=c++11]”。
【问题讨论】:
标签: c++ windows c++11 error-handling strtol