检查有效输入

发布于 2024-10-02 08:28:38 字数 638 浏览 0 评论 0原文

我目前正在开发一个 C++ 程序,我想检查用户所做的输入是否有效。目前,如果用户输入正确的输入,或者如果用户输入一个小的错误数字,我的代码就会工作,我的程序将告诉用户该输入无效。现在我的问题是,当用户输入多个字符/字母或包含 9 个或更多数字的大数字时,我的程序会进入无限循环,并给出错误消息。以下是我的代码:

//for (;;)
    while (flag== false)
    {
        cin >> Input;
        if (Input <= choice.size()-1)
        {
            flag = true;
    //  break;
        }

        else
        {
            cerr << "Input <" << Input << "> is Invalid, Please Choose a Valid Option\n";
            userInput = 0;
        }
    }

如您所见,我也尝试过执行无限 for 循环,但它给出了相同的结果。 在我的代码中,我将矢量打印到屏幕上。基本上,用户选择向量值来使用它。

我愿意接受任何建议。谢谢

I am currently working on a c++ program and I want to check to see if the input the user is making is valid. Currently my code works if the user inputs the proper input or if the user inputs a small incorrect number my pogram will tell the user that the input is invalid. Now my problem is that when the user inputs multiple characters/letters or a large number that has 9 or more digits in it my program goes into an infinate loop giving them the error message. The following is my code:

//for (;;)
    while (flag== false)
    {
        cin >> Input;
        if (Input <= choice.size()-1)
        {
            flag = true;
    //  break;
        }

        else
        {
            cerr << "Input <" << Input << "> is Invalid, Please Choose a Valid Option\n";
            userInput = 0;
        }
    }

As you can see I have also tried doing an infinate for loop but it gives me the same results.
In my code i am printing a vector to the screen. Basicly the user it picking the vectors value to use it.

I am open to any suggestions. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冰葑 2024-10-09 08:28:38

如果用户输入的内容无法读入 Input(从代码中不清楚 Input 是什么类型),该输入将卡在输入流中并且循环的每次迭代都将无法读取输入,直到清除流为止。

每次读取失败后,您需要清除流标志并清除流中等待的任何错误输入。尝试这样的事情:

while(!(cin >> Input) || Input <= choice.size()-1)
{
  cerr << "Input <" << Input << "> is Invalid, Please Choose a Valid Option\n";
  cin.clear(); // Clears the input stream fail flag
  cin.ignore(100, '\n'); // Ignores any characters left in the stream
}

If the user types in something that can't be read into Input (it's not clear from your code what type Input is), that input will get stuck in the input stream and each iteration of the loop will keep failing to read in the input until you clear the stream.

You need to clear the stream flags and get rid of whatever bad input is waiting in the stream after each failure to read. Try something like this:

while(!(cin >> Input) || Input <= choice.size()-1)
{
  cerr << "Input <" << Input << "> is Invalid, Please Choose a Valid Option\n";
  cin.clear(); // Clears the input stream fail flag
  cin.ignore(100, '\n'); // Ignores any characters left in the stream
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文