【问题标题】:How to allow user to do input more than twice?如何允许用户输入两次以上?
【发布时间】:2014-08-19 05:26:33
【问题描述】:

我是 C++ 新手。我试图了解如何利用 C++ 通用输入 (cin)。我正在尝试编写一个程序来检查句子的字符数量和输入句子中元音的数量。我已经成功地做到了,但是当我尝试让代码再运行一次时会出现问题。当它再次运行时,它不再允许第二次输入。我的简化代码如下。

#include <iostream>
#include <string>

using namespace std;

int main()
{
  char rerun = 'y';
  string input;
  int a_counter, e_counter, i_counter, o_counter, u_counter;
  a_counter = e_counter = i_counter = o_counter = u_counter = 0;

  do
  {
    getline(cin, input); // asking user to input a sentence
    // already written code here that uses for loop to do the vowel counting
    // already written code to use the cout command to output the result
    cin >> rerun; // ask to type 'y' or 'n' to continue, assume user only types y or n
  } while (rerun == 'y');
} //end of main function

运行此程序时,首先允许用户输入一个句子,输入和结果显示后,要求用户输入'y'或'n'。如果答案是 y,代码将不允许输入句子(getline 所在的位置)并显示所有结果(a_counter...)都为 0,并直接跳回请求输入“y”或“n”。有人可以帮助我吗?将不胜感激。

【问题讨论】:

    标签: c++ loops input cin getline


    【解决方案1】:

    当行

    cin >> rerun;
    

    被执行,'\n' 留在输入流中。下次你跑

    getline(cin, input);
    

    你得到一个空行。

    要解决问题,请添加该行

    cin.ignore();
    

    紧接着

    cin >> rerun;
    

    你的循环应该是这样的:

    do
    {
      getline(cin, input);
      cin >> rerun;
      cin.ignore();
    }while (rerun == 'y');
    

    【讨论】:

    • 谢谢,它有效,帮助很大!请问这个问题什么时候出现,什么时候需要使用cin.ignore()?
    • @user3595342,很高兴它成功了。当您想在格式化读取后忽略一行的剩余部分时,可以使用cin.ignore()
    【解决方案2】:

    这里发生的问题是当您在输入yn 之后输入\n 被视为rerun 的字符输入,因此条件变为错误..

    让我们尝试了解您的代码中发生了什么。 假设您正在提供输入

    abcde(\n)

    y(\n)

    abc(\n)

    字符串在遇到\n..so 时终止

    input = "abcde"(这里没问题)

    现在,当您在rerun 中输入y(\n) 时,它可以..条件变为true,但问题从这里开始..\n 现在采用input..即

    重新运行 = 'y'

    input = '\n'(只会打印一行什么都没有的..试试cout)

    现在一旦你输入一些东西,假设它会进入input,它不会真的发生,但实际上它进入了rerun(因为input已经包含@ 987654335@),如果不是y,它将被评估false..希望我很清楚

    这是另一种方法

    #include <string>
    #include <cstdio>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        char eatNewline = '\0';
        char rerun = 'y';
        string input;
        int a_counter, e_counter, i_counter, o_counter, u_counter;
        a_counter = e_counter = i_counter = o_counter = u_counter = 0;
    
        do {
            getline(cin, input);
            cin >> rerun;
            eatNewline = getchar();
        } while (rerun == 'y');
    
     return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-18
      • 1970-01-01
      • 2015-01-03
      • 2015-07-14
      • 1970-01-01
      • 2021-02-08
      • 2019-07-30
      • 1970-01-01
      • 2018-01-22
      相关资源
      最近更新 更多