【问题标题】:while loop and getchar()while 循环和 getchar()
【发布时间】:2015-06-04 01:02:28
【问题描述】:

下面是我为大学课程编写的简单程序。我知道它并没有真正做任何事情,但这只是一门课程的作业。

我想不通的部分是,为什么外循环不起作用?

用户需要按“1”继续,程序退出任何其他键。

但是,如果用户按“1”并退出,它仍然不会继续。

我尝试在 cin >> 重复之前添加一个 cin.clear() ,但这不起作用。

我也尝试过使用 cin.ignore(),但这似乎也没有帮助。

有什么想法吗?

谢谢

int main()
{
    int repeat = '1';
    stack<char> cstr;
    char c;

    while (repeat == '1')
    {
        cout << "Enter in a name: ";

        while (cin.get(c) && c != '\n')
        {
            cstr.push(c);
        }

        cout << "\n Enter another name? 1 = Continue, any other key to exit the program";
        cin >> repeat;
        repeat = getchar();
   }
}

【问题讨论】:

  • 为什么要将字符串分配给整数重复?
  • @reggie 这不是字符串,而是字符。
  • cin &gt;&gt; repeat; 之后,您希望在repeat 中出现什么? 那么repeat = getchar()之后会是什么?

标签: c++ c++11 visual-c++


【解决方案1】:

您的代码没有任何问题。对我来说似乎工作正常。

编辑:抱歉,在您删除 getchar 之前它不起作用。忘了提那个。找出错误的简单方法是仅显示变量 repeat 的值以查看该值是什么以及出错的地方。

显示您的代码有效的屏幕截图

一切似乎都运行良好。不过,我想评论一下您的程序结构。对于像这样的小程序,没关系,但总是最好按照逻辑方式进行练习。对于这样的问题,您应该实现 do while 循环而不是 while 循环,以便它无需检查即可进入,然后接受用户输入并检查后置条件。下面的例子。

    char  repeat;

    do
    {
        //Your codes in here
    }while (repeat == '1');

除非您的问题指定您使用 while 循环,否则使用此方法更合乎逻辑。无论如何希望这会有所帮助。

【讨论】:

    【解决方案2】:

    运行这个。它会以某种方式解决您的问题,repeat=getchar 使 repeat=10。

     int main()
        {
        char  repeat = '1';
        stack<char> cstr;
        char c;
    
        while (repeat == '1')
        {
            cout << "Enter in a name: ";
            cin.ignore();
            while (cin.get(c) && c != '\n')
            {
                cstr.push(c);
            }
    
            cout << "\nEnter another name ? \nPress 1 to Continue : ";
            cin >> repeat;
            cout << endl;
        }
        system("pause");
        }
    

    【讨论】:

    • 你有没有运行过这段代码。它按你的意愿工作。第一个问题是外循环不起作用,然后是它没有接受输入。
    【解决方案3】:

    cin &gt;&gt; repeat 行正在尝试从键盘读取整数,因为repeatint 类型的变量。但是,您正在验证从键盘读取的整数是否等于 49(字符“1”的 ASCII 代码),这不是您想要的。一个解决方案是替换该行

    int repeat = '1';
    

    int repeat = 1;
    

    也替换

    while (repeat == '1')
    

    while (repeat == 1)
    

    因为您将从键盘读取的整数与整数 1(而不是 字符“1”)进行比较。此外,在循环结束时,您从键盘读取输入并将其存储在repeat 中,但随后您立即再次读取输入并将该值存储repeat 中,替换其先前的值。要解决此问题,请替换行

    repeat = getchar();
    

    getchar();
    

    应该这样做。

    【讨论】:

      【解决方案4】:
         cin >> repeat; 
      

      它将repeat 读取为int。 (1不等于'1')

      repeat = getchar();
      

      它读取特殊字符'\n'的int代码 - 行尾符号。

      你必须使用

      char repeat = '1';
      

      或者写

      int repeat = 1;
      

      不使用 getchar()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-18
        • 2011-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-10
        相关资源
        最近更新 更多