0

What seems to be the problem in my code?

When I hit Enter after entering my age, the prompt already finishes without asking for my address. I know I can use getline() for the age, but what if the user enters a non-integer answer?

Sorry, I just started coding yesterday and I want to learn the basics.

#include <iostream>

using namespace std;

int main()
{
    int age;
    string name, address;

    cout << "Please enter the name of the user:" << endl;
    getline(cin, name);

    cout << "Please enter age of the user:" << endl;
    cin >> age;

    cout << "Please enter the address of the user:" << endl;
    getline(cin, address);

    cout << "Your name is " << name << " and you are " << age 
     << " years old " << " who lives in " << address << endl;

    cout << "Thank you for using my program!";


    return 0;
}
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
  • 3
    You are mixing `getline` with `cin >> whatever` calls. That usually leads to madness. – Eljay Mar 02 '19 at 04:55
  • `getline` extracts the `'\n'` from the input stream, `cin` doesn't. After `cin` the `'\n'` remains in the input stream and since `getline` only reads until it encounters `'\n'` it reads nothing and appears to skip to the second `getline` prompt. – David C. Rankin Mar 02 '19 at 05:05
  • First see why are you using two different ways of input: getline(cin, ) and cin>> ? If you can answer this, you'll get answer to your question. So just see the documentation of getline and find out how it is different from cin>> – Nitesh Mar 02 '19 at 05:10
  • Your problem is answered by the mentioned duplicate already. However, as a new user here, take the [tour] and read [ask], too! – Ulrich Eckhardt Mar 02 '19 at 05:15
  • See [this answer](https://stackoverflow.com/a/54954818/65863) that I posted earlier today to another question, it can be applied to this question, too. – Remy Lebeau Mar 02 '19 at 05:45

1 Answers1

1

Just add 'cin.ignore()' after 'cin>>age' like this:

cout << "Please enter age of the user:" << endl;
cin >> age;
cin.ignore();
cout << "Please enter the address of the user:" << endl;
getline(cin, address);

When getline() reads input, then a newline character is left in input stream, due to which it dosen't reads the string(address) in your program.

And if a user enters a 'float' or 'double' etc. instead of 'int' in age then it will simply extract out integer from it , for example: if user enters 39.29 or 39.00005 or 39.00 or then age=39

To know more about getline check the following link:

neelesh bisht
  • 410
  • 3
  • 8