【问题标题】:How to loop the getline function in C++ [duplicate]如何在C ++中循环getline函数[重复]
【发布时间】:2021-12-17 08:43:33
【问题描述】:

谁能向我解释为什么我的代码中的 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-structures while-loop cin getline


    【解决方案1】:

    试试这个:

    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

    【讨论】:

    • 小心,这只有在他们输入“{age}[newline]”而不是“{age}[space][newline]”或任何其他组合时才有效。
    • 以前从未尝试过,因为控制台应用程序主要是家庭作业,非常棒。如何预防?
    • 该行解决了我的问题,我需要查看 cin.get() 函数以了解发生了什么。
    • 但是正如@scohe001 提到的,如果您尝试用空格输入“19”并按回车,问题将再次出现。更安全的解决方案是将该行更改为 std::cin.ignore(10000, '\n');
    • 我喜欢忽略最大字符数的限制。惯用的版本是 cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\n'),但通常如果您要查找超过几百个字符来查找行尾,则出现了非常非常错误的情况,您应该停下来找出原因。
    猜你喜欢
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多