c++ - while 循环接受第一个和第二个 cin 的输入

标签 c++ while-loop cin

我编写这些代码行的目的是创建一个程序来显示用户键入的短语有多少个字符。我用另一个任务完成了我的代码行,为用户创建一个提示来结束程序或循环它。为此,我创建了一个 while 循环。一切顺利,直到系统提示我“再去一次?”。无论我键入什么输入,它都会自动为我提供第一个输入的输出,这意味着它也为我的第一个 cin 接收输入。作为引用,这是我的代码:

#include <iostream>
#include <string.h>
#include <stdlib.h>

using namespace std;

int main()
{
char again = 'y';
string phrase;
while (again == 'y' || again == 'Y')
{

cout << "Enter your phrase to find out how many characters it is: ";
getline(cin,phrase);
cout << phrase.length() << endl;
cout << "Go again? (y/n) " ;

cin >> again;

}
cout << "The end." << endl;

system ("pause");
}

抱歉,如果我的问题含糊不清或使用了错误的术语,我才刚刚开始学习 C++。

谢谢。

最佳答案

您应该在 cin>> 之后再次添加 std::cin.ignore()

#include <iostream>
#include <string.h>
#include <stdlib.h>

using namespace std;

int main()
{
char again = 'y';
string phrase;
while (again == 'y' || again == 'Y')
{

cout << "Enter your phrase to find out how many characters it is: ";
getline(cin,phrase);
cout << phrase.length() << endl;
cout << "Go again? (y/n) " ;

cin >> again;
cin.ignore();
}
cout << "The end." << endl;

system ("pause");
}

问题在于,在 std::cin 之后,新行仍将保留在输入缓冲区中,而 getline() 将读取该新行。 std::ignore() 只会从输入缓冲区中抓取一个字符并将其丢弃。

有关更多信息,请参阅 http://www.augustcouncil.com/~tgibson/tutorial/iotips.html#problems

关于c++ - while 循环接受第一个和第二个 cin 的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55259527/

相关文章:

r - 如何在While循环中有两个条件?

c++ - 无效数字总是降为 0?

C++ getline();下面显示一个

c++ - 为什么这个 C++ 代码在每一行之后打印一个?

c++ - 为什么我不能对另一个类的静态 char[] 执行 sizeof?

c++ - 在 C/C++ 中检测运行时变量的修改

c - 在没有整数的情况下重新启动c中的while循环

c - 我应该如何在用户输入时停止 C 循环

c++ - 虚拟模板方法有意义吗?

c++ - 生成文件错误 3