我试图确保用户输入是一个正整数,并且无论用户尝试输入什么,我的函数都能正常工作。
int getNumber()
{
string userInput;
int userNumber;
bool badInput = true;
cout<<"Enter a positive integer: ";
cin>>userInput;
while (badInput)
{
for (int i=0; i<userInput.length(); i++)
{
if (isdigit(userInput[i]))
{
badInput = false;
}
else
{
badInput = true;
cout<<"That wasn't a valid input, try again: ";
cin>>userInput;
break;
}
}
}
userNumber = atoi(userInput.c_str());
return userNumber;
}
是否有更简洁的方法或者这是最好的方法?我尝试了各种其他方法,例如使用 cin.bad 等,但它们总是设法遗漏一些问题。
最佳答案
如果你需要检查一个正整数,你可能需要 将文本也转换为整数。你应该两者都做 立刻;类似的东西:
std::string line;
if ( !std::getline( std::cin, line ) ) {
// no input available...
} else {
std::istringstream parser( line );
int userNumber;
if ( parser >> userNumber >> std::ws
&& parser.get() == EOF
&& userNumber > 0 ) {
// All OK...
} else {
// Some error in the input.
}
}
也可以使用 strtol
,如果你有来自
别处。错误检测有点棘手,因为 strtol
在某些情况下有一些奇怪的语义:
int
getPositiveInteger( std::string const& input )
{
char const* end;
errno = 0;
long results = strtol( input.c_str(), &end, 10 );
if ( end != input.c_str() ) {
while ( isspace( static_cast<unsigned char>( *end) ) ) {
++ end;
}
}
return (errno == 0
&& end != input.c_str()
&& *end == '\0'
&& results > 0
&& results <= INT_MAX)
? results
: -1;
}
(如果出现错误,我已返回 -1。)
您会注意到必须测试的条件数量
确保 stdtol
工作正常。
关于c++ - 检查输入是一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14999105/