尝试使用while语句验证用户输入C ++ [英] Trying to use a while statement to validate user input C++

查看:271
本文介绍了尝试使用while语句验证用户输入C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新的C ++和我在一个类。我试图完成第一个项目,到目前为止我所有的一切工作正常,但是,我需要用户输入一个数字来选择他们的水平,并希望验证它是一个数字,并且该数字不是太大。

I am new to C++ and am in a class. I am trying to finish the first project and so far I have everything working correctly, however, I need the user to input a number to select their level, and would like to validate that it is a number, and that the number isn't too large.

while(levelChoose > 10 || isalpha(levelChoose))
{
    cout << "That is not a valid level" << endl;
    cout << "Choose another level:";
    cin >> levelChoose;
}

这是我做的循环,它有时工作。如果我输入11打印错误,让我选择另一个级别。然而,如果数字很大,或者是任何字母字符,它洪水屏幕的cout,循环不会结束,我必须强制退出。为什么它有时停在cin和等待用户输入,有时不?感谢您的帮助!

That is the loop I made, and it sometimes works. If I type in 11 it prints the error, and lets me choose another level. However if the number is large, or is any alpha character it floods the screen with the couts, and the loop won't end, and I have to force exit. Why does it sometimes stop at the cin and wait for user input, and sometimes not? Thanks for the help!

推荐答案

这是一个恼人的问题与通常的cin cin是类型安全所以如果你给它错误的类型,它会失败。正如你所说的一个非常大的数字或非数字输入,它被困在一个无限循环。这是因为那些与任何类型levelChoose可能是不兼容。 cin失败,但缓冲区仍然填充你输入的内容,所以cin不断尝试读它。

This is an annoying problem with cin (and istreams in general). cin is type safe so if you give it the wrong type it will fail. As you said a really large number or non-number input it gets stuck in an infinite loop. This is because those are incompatible with whatever type levelChoose may be. cin fails but the buffer is still filled with what you typed so cin keeps trying to read it. You end up in an infinite loop.

要解决这个问题,您需要清除失败位并忽略缓冲区中的所有字符。下面的代码应该这样做(虽然我没有测试它):

To fix this, you need to clear the fail bit and ignore all the characters in the buffer. The code below should do this (although I haven't tested it):

while(levelChoose > 10 || isalpha(levelChoose))
{
    cout << "That is not a valid level" << endl;
    cout << "Choose another level:";
    if(!(cin >> levelChoose))
    {
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}

编辑:numeric_limits<>位于:

numeric_limits<> is located in the limits include:

#include<limits>

这篇关于尝试使用while语句验证用户输入C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆