如何允许用户进行两次以上的输入
How to allow user to do input more than twice?
我是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');
这里发生的问题是当您在输入y
或n
后输入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;
}
相关文章:
- 在指定的响应之前C++用户输入两次
- 将用户输入验证为整数:用户必须两次输入输入
- C++使用二维数组的程序,该数组要求用户输入两次.它需要将这些输入显示为输出
- 如何修复密码条目,它一次输入两个字符
- 为什么输入文件的最后一行运行两次?
- cin.ignore() 输入两次以获得一次暂停
- 为什么在这里对c++输入文件流进行两次检查
- C 必须将输入输入两次
- 重复上一次输入两次
- C++程序要求我输入两次,即使变量第一次被分配
- c ++ 如何阻止我的循环两次吐出最后一个输入
- 函数读取输入并运行函数两次
- 为什么我必须输入两次
- 如何在获得下一个字符后正确刷新输入缓冲区,而无需按两次回车键!C++
- 为什么 ifstream 返回输入文件的最后一个值两次
- 尝试从输入文件打印,但打印最后一个输入两次
- 为什么我的代码要求"请输入 2-12 之间的数字:"两次?
- 两次读取std::cin的输入
- 如何阻止用户两次输入相同的值
- Boost接受器每次接受两次输入连接,并生成两个线程