c++ - 如何在 C++ 中循环 getline 函数
问题描述
谁能向我解释为什么我的代码中的getline()语句没有像我预期的那样循环,我希望while循环中的代码永远执行,但是我的代码只循环代码但跳过了getline()函数。我将提供屏幕截图...我的代码是:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int age;
while(true)
{
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your age: ";
cin >> age;
cout << "Age: " << age << "\tName: " << name << "\n\n";
}
}
解决方案
尝试这个:
while(true)
{
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your age: ";
cin >> age;
cout << "Age: " << age << "\tName: " << name << "\n\n";
cin.get(); //<-- Add this line
}
编辑: std::cin.ignore(10000, '\n'); 是一个更安全的解决方案,因为如果您使用 cin.get(); 并输入“19”或其他年龄组合,问题将重演。
感谢@scohe001
最后:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int main()
{
int age;
string name;
while(true)
{
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your age: ";
cin >> age;
cout << "Age: " << age << "\tName: " << name << "\n\n";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
感谢@user4581301
推荐阅读
- python - 使用 numpy 语法对 self 进行共轭转置
- python - Five9 API python 包装器 - runReport
- css - 如何实现Materialize CSS masonry-like列,卡片水平排列而不是垂直排列
- linux - 使用 awk 重新格式化数据
- tfs - MTM/VSTS“插入共享步骤”查询每个用户有不同的默认值
- .htaccess - 如何在网址中添加斜杠?
- python - 如何在启动画面中插入图片?
- mule - 骡流没有触发
- gradle - com.jfrog.artifactory gradle 插件 401 未经授权
- python - 求和的指数