如何允许用户进行两次以上的输入

How to allow user to do input more than twice?

本文关键字:两次 输入 用户 何允许      更新时间:2023-10-16

我是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'。有人能帮帮我吗?非常感谢。

cin >> rerun;
执行

,则将'n'留在输入流中。下次运行

getline(cin, input);

你得到一个空行。

要解决这个问题,添加

cin.ignore();

紧跟在

后面
cin >> rerun;

循环应该是这样的:

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

这里发生的问题是当您在输入yn后输入n时被视为rerun的字符输入,因此条件变为假…

让我们试着理解你的代码中发生了什么。假设输入

中的( n)

y ( n)

abc ( n)

字符串在遇到n ..时终止,因此

input = "abcde"(没有问题)

现在,当你在rerun中输入y(n)时,情况变成了true,但问题从这里开始,n现在出现在input中,即

rerun = 'y'

input = 'n'(只打印没有任何内容的行…试试输入cout)

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

这里有另一种方法

#include <string>
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
    char eatNewline = '';
    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;
}