如何验证数字输入C++

Raú*_*Roa 6 c++ visual-c++

我想知道如何使用输入值限制为带符号的小数std::cin.

aru*_*rul 11

如果后缀变量cin是一个数字,并且提供的字符串不是数字,则返回值为false,因此您需要一个循环:

int someVal;

while(!(cin >> someVal)) {
   cin.reset();
   cout << "Invalid value, try again.";
}
Run Code Online (Sandbox Code Playgroud)

  • play.cpp:10:错误:'struct std :: istream'没有名为'reset'的成员 (10认同)
  • 而且 - 如果我用clear()替换reset(),你意味着与否 - 当给出非数字输入时,它会导致无限循环. (6认同)

Raú*_*Roa 7

double i;

//Reading the value
cin >> i;

//Numeric input validation
if(!cin.eof())
{
    peeked = cin.peek();
    if(peeked == 10 && cin.good())
    {
             //Good!
             count << "i is a decimal";
        }
        else
        {
             count << "i is not a decimal";
         cin.clear();
         cin >> discard;
        }
}
Run Code Online (Sandbox Code Playgroud)

这也会给出一条错误消息,其中输入 -1a2.0,避免仅将 -1 分配给 i。