atoi
の代わりにstrtol
を使用するべきであると聞いたことがあります。私は、文字列が整数であるかどうかを確認するために、このコードを使用することができるかどうかを確認したかった。C++:文字列が "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、これを返します:
testString = 2147483648
errno = 34
There was an error.
testInt = 2147483647
十分に適切です。私はHello world!
でそれをしようとする。しかし、これはアップします:
testString = Hello world!
errno = 0
Success.
testInt = 0
私はここで行うことを意図していますか?そして、文字列がintであることを確認するだけで、何かのために複雑なものを私に与えないでください。使用
:GNU GCCコンパイラ、コード::ブロック、Windowsの
は "G ++続くC++ 11 ISO C++言語の標準[-std = C++ 11]があり、" "コンパイラフラグ" にチェックされています。
[NULL]の代わりに適切な引数を[strtol](http://www.cplusplus)に渡してください。com/reference/cstdlib/strtol /)を使用して有効な範囲を知ることができます。 – Jarod42
あなたの2番目のテストケースのために[No repro](http://coliru.stacked-crooked.com/a/021660de72cf66f4) –
@πάνταῥεῖ、それは 'long'がその番号を保持できるかどうかによって異なります。 32ビットの「long」はできません。 – chris