尝试使用 while 语句来验证用户输入 C++

时间:2023-01-21
本文介绍了尝试使用 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,它会打印错误,并让我选择另一个级别.但是,如果数字很大,或者是任何字母字符,它会用 couts 淹没屏幕,并且循环不会结束,我必须强制退出.为什么它有时会停在 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(以及一般的 istreams)的一个恼人的问题.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(), '
');
    }
}

numeric_limits<>位于limits include:

numeric_limits<> is located in the limits include:

#include<limits>

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

上一篇:如何在 C++ 中将用户输入验证为双精度值? 下一篇:如何将 std::chrono::time_point 转换为带小数秒的日历日期时间字符串?

相关文章

最新文章