【问题标题】:cin.get(); doesn't work when I put it in a if statementcin.get();当我把它放在 if 语句中时不起作用
【发布时间】:2014-02-06 16:57:30
【问题描述】:

我使用 cin.get() 让程序暂停并等待用户输入,它工作正常。我把它放在 if 语句中的那一刻,它只是跳过那个“等待”期并继续代码?我该如何解决这个问题。这是不工作的部分。

  do
    {
        cout << "\n\n\nEnter the number of one of the following and I will explain!\n";
        cout << "1.integer  2.boolian   3.floats   4.doubles   5.character";
        cout << "\n\n[when you are done type 'done' to continue]\n\n";
        cin >> option;

        if (option = 1);
        {
            cout << "\nInteger is the variable abbreviated as 'int' this allows C++ to only";
            cout << "\nreadwhole and real numbers \n\n";
            cin.get(); //this is the part where it just skips.. it should wait
        }

    } while (var = 1);

【问题讨论】:

  • 正如@0x499602D2 在我的回答中在 cmets 中指出的那样,您还有很多其他问题。确保您阅读了这些 cmets。

标签: c++


【解决方案1】:

问题在于cin &gt;&gt; option 将提取输入流中的任何整数,但会留下以下换行符(在输入值后按回车键即可)。当您执行cin.get() 时,它只是提取已经存在的换行符。像这样的许多其他问题一样,解决方案是在您提取到option 后清空输入流:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

您还使用了赋值 (=) 来比较是否相等 (==)。

【讨论】:

  • +1 还有while (var = 1)if (option = 1);。 :)
  • @0x499602D2 谢谢,没注意到。将其添加到我的答案中。
  • 没问题。但他在if (option = 1);中也有一个分号
猜你喜欢
  • 2016-01-28
  • 1970-01-01
  • 2023-03-16
  • 2014-06-19
  • 2019-01-26
  • 1970-01-01
  • 2022-07-01
  • 2016-02-17
  • 2017-05-22
相关资源
最近更新 更多