c++ - While 循环接受第一个和第二个 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++。
谢谢。
解决方案
您应该std::cin.ignore()
在cin>>again
.
#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
推荐阅读
- rsyslog - rsyslog 服务器生成以 IP 地址而不是 access_log 命名的日志文件
- postgresql - 如何根据用户查询数据在视图中设置动态“位置”?
- python - 使用 Python 将两个 CSV 文件与案例合并
- javascript - Angular Tooltip 显示在错误的 Ag-Grid 单元格上
- flutter - 在 setState 更改流后 StreamBuilder 不会重建
- reactjs - 在反应应用程序中更新反应脚本后出错
- python-3.x - 在多索引数据框中合并两个数据系列
- customization - 如何自定义 vimeo 字幕的样式?
- c# - 在剃刀页面中动态更改按钮标签文本
- sql - 无法删除视图的 Flyway 可重复迁移