0

I've encountered a problem with getline(). I've googled it and checked multiple pages, but those answers aren't meant for newbies like me. Here's the code: #include <iostream> #include <string.h> using namespace std; int main(){ string n,s,a,ad,e; cout<<"Your name: "<<endl; cin>>n; cout<<"Hello, "<<n<<endl; cout<<"Your surname: "<<endl; cin>>s; cout<<"Your age: "<<endl; cin>>a; cout<<"Your address: "<<endl; getline(cin,ad); cout<<"Your email: "<<endl; cin>>e; cout<<"Done."<<endl; cout<<"Name: "<<n<<" "<<s<<endl; cout<<"Age: "<<a<<endl; cout<<"Address: "<<ad<<endl; cout<<"Email: "<<e<<endl; } The problem is that the getline(cin,ad) just skips whenever I launch the program. It goes this way: Your name: name Hello, name Your surname: surname Your age: age Your address: Your email: As you can see, I can't enter my address, because the getline() gets skipped. How can I fix this, simply?

I solved the problem, I just should've written:

cin>>ad;
getline(cin, ad);

and that's all. Thanks for your contribution!

  • 1
    You are mixing `getline` and stream extraction using `operator>>`. After the `cin>>a` you probably want to do `cin.ignore(ignore(std::numeric_limits::max(), '\n');` to clear out the rest of the line for the age input. – Eljay Oct 03 '21 at 12:22

1 Answers1

0

Don't mix getline and >>.

The user will always press Enter after every input you ask for.

In general, use getline to get user input. If you need further processing afterwards, use a stringstream or one of the standard string-to-integer or string-to-float functions.

In your case, everything you ask for is a string, so there isn't any point in using anything but getline anyway.

(Especially when it comes to names.)

Dúthomhas
  • 8,200
  • 2
  • 17
  • 39