标准输入(cin)跳过While循环

时间:2014-07-01 19:23:25

标签: c++ loops while-loop cin

体验

我对C ++比较陌生,所以这里可能会出现一些noob错误......

方案

我需要检查给定的输入是否为整数,如果不是,请继续询问它,直到输入为整数。一些变量和字符串说"页面"是因为用户需要输入小册子的页数。

问题

我的问题是,当通过故意输入一个字母来测试我的代码(代码块1)时,循环跳过请求一些标准输入(cin)并在每次迭代时继续循环,从而产生无限循环的"输入不是整数!"和"请输入页数:"。

研究与发展调试

我查看了here以了解如何检查输入是否为整数并使用了aam1r的答案的第一部分。在开始if陈述之前,他的答案中的第二个建议需要输入两次。我无法在互联网上找到任何使用cin循环中使用while的代码的内容,而不是条件。

我在每个语句之间插入代码,该语句打印字母表的字母以显示循环的位置,这可以在代码块2中看到。重复的字母是de,{ {1}}和f,因此g被忽略,因为我们没有提示输入整数,我认为它使用了最后一个已知的输入,这是一个字母,所以无限环路。

问题

  1. 为什么要跳过cin >> page_no;?如果原因不能用于修复现有代码,
  2. 有没有其他方法可以做到这一点?
  3. 代码

    第1区 - 没有调试代码

    cin >> page_no;

    第2块 - 使用调试代码

    unsigned short int page_no;
    
    cout << "Please enter the number of pages (must be divisible by 4): ";
    cin >> page_no;
    
    // Testing integer checking
    if (!cin)
      {
        bool notint(true);
        cout << "Input was not an integer!" << endl << "Please enter the number of pages: ";
        while (notint)
          {
            cin >> page_no;
            if (!cin)
              {
                cout << "Input was not an integer!" << " Please enter the number of pages: ";
              }
            else
              {
                notint = false;
              }
          }
      }
    

    输出(Bash Shell)

    unsigned short int page_no;
    
    cout << "Please enter the number of pages (must be divisible by 4): ";
    cin >> page_no;
    
    // Testing integer checking
    if (!cin)
      {
        cout << "a" << endl;
        bool notint(true);
        cout << "b" << endl;
        cout << "Input was not an integer!" << endl << "Please enter the number of pages: ";
        cout << "c" << endl;
        while (notint)
          {
            cout << "d" << endl;
            cin >> page_no;
            cout << "e" << endl;
            if (!cin)
              {
                cout << "f" << endl;
                cout << "Input was not an integer!" << " Please enter the number of pages: ";
                cout << "g" << endl;
              }
            else
              {
                notint = false;
              }
          }
      }
    

    编辑: 我的问题是为什么Please enter the number of pages (must be divisible by 4): e a b Input was not an integer! Please enter the number of pages: c d e f Input was not an integer! Please enter the number of pages: g d e f Input was not an integer! Please enter the number of pages: g 被跳过了?但是在那些假设我首先想要解决方案后的评论中回答了这个问题。

0 个答案:

没有答案
相关问题