首页 > 解决方案 > 如何在 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";
    }
}

输出仅循环cin函数,到目前为止我还没有找到可以让事情变得清晰的解决方案。我的代码运行如下: 我的代码运行后的图像

标签: c++data-structureswhile-loopcingetline

解决方案


尝试这个:

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


推荐阅读