如何允许用户进行两次以上的输入? [英] How to allow user to do input more than twice?

查看:85
本文介绍了如何允许用户进行两次以上的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to C++. I am trying to understand how to utilize the C++ common input (cin). I am trying to write a program that checks the amount of characters of the sentence and the amount of vowels in the input sentence. I have successfully done it, but a problem happens when I try to get the code to run through one more time. When it runs through one more time, it doesn't allow second input anymore. My simplified code is below.

#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".有人可以帮我吗?非常感谢.

When running this program, at first user would be allowed to input a sentence and, after the input and the result are displayed, user is asked to put in 'y' or 'n'. If answer is y, the code would not allow to put in the sentence (where getline is) and display result of everything (a_counter...) are all 0 and jump straight back to requesting to put 'y' or 'n'. Can somebody help me? It would be much appreciated.

推荐答案

当行

cin >> rerun;

执行

时,'\n'留在输入流中.下次您运行

is executed, the '\n' is left in the input stream. Next time you run

getline(cin, input);

您会得到一个空行.

要解决此问题,请添加行

To fix the problem, add the line

cin.ignore();

紧接着

cin >> rerun;

这是您的循环的外观:

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

这篇关于如何允许用户进行两次以上的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆