如何在 C++ 中循环 getline 函数
How to loop the getline function in C++
任何人都可以向我解释为什么我的代码中的 getline() 语句没有像我预期的那样循环,我想要 while[ 中的代码=20=] 循环永远执行但是我的代码只循环代码但跳过 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";
}
}
输出仅循环 cin 函数,到目前为止我还没有找到任何解决方案来说明问题。我的代码运行如下:
试试这个:
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
任何人都可以向我解释为什么我的代码中的 getline() 语句没有像我预期的那样循环,我想要 while[ 中的代码=20=] 循环永远执行但是我的代码只循环代码但跳过 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";
}
}
输出仅循环 cin 函数,到目前为止我还没有找到任何解决方案来说明问题。我的代码运行如下:
试试这个:
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