1

Can anyone explain to me why my getline() statement from my code is not looping as I could expect, I want the code inside the while loop to execute forever but then my code only loops the code but skips the getline() function. I'll provide the screenshot...my code is:

#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";
    }
}

the output loops only the cin function and no solution I have found so far that put things clear. My code runs like: The Image of my code after running it

Georgey
  • 23
  • 6

1 Answers1

1

Try this:

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
    }

Edit: std::cin.ignore(10000, '\n'); is a safer solution since if you use cin.get(); and type "19 " or other combinations for age, the problem will repeat itself.

Thanks to @scohe001

Final:

#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');
    }
}

Thanks to @user4581301

SBU
  • 194
  • 9
  • 3
    Careful, this'll work only if they've entered "{age}[newline]", not "{age}[space][newline]" or any other combination. – scohe001 Nov 02 '21 at 21:11
  • Never tried that before since the console applications were mostly homeworks, great catch. How to prevent that? – SBU Nov 02 '21 at 21:19
  • The line solved my problem, I'll need to look into the **cin.get()** function to understand what happened. – Georgey Nov 02 '21 at 21:20
  • But as @scohe001 mentioned, if you try to type "19 " with a space and press enter the problem will repeat itself. A safer solution is changing that line to std::cin.ignore(10000, '\n'); – SBU Nov 02 '21 at 21:22
  • @Supreme `get()` simply reads one character from the stream (and it is discarded, since there return value is not saved into any variable). For an actual detailed answer, see the duplicate question. – Yksisarvinen Nov 02 '21 at 21:24
  • 3
    I like the limitation on the maximum number of characters ignored. The idiomatic version is `cin.ignore(numeric_limits::max(), '\n')`, but typically if you're chucking more than a few hundred characters to find the end of the line, something has gone very very wrong and you should probably stop and find out what. – user4581301 Nov 02 '21 at 21:24