简体   繁体   中英

Getline always ignoring first word of input c++

I'm having trouble with this code. I want it to take 2 words and it's always ignoring the first word and then taking the 2nd word. If I put in 3 words, it works perfectly and picks up the final 2 words. The prompt for this is these bullet points.

  • Prompt the user to enter his/her first and last name.
  • Read the name from the keyboard using the getline method and store it into a variable called fullName (you will need to declare any variables you use).
  • Print out the fullName.
  • Compile, debug, and run, using your name as test data.
  • Since we are adding on to the same program, each time we run the program we will get the output from the previous tasks before the output of the current task.

How do you make this work correctly?

string fullName;
cout << "What is your full name" << endl;
    cin >> fullName;
getline(cin, fullName);
    cout << fullName << endl;
cout << endl;
cin >> fullName;

reads the first word of the full name.

getline(cin, fullName);

reads the rest of the name over top of the first word . Computer programs do exactly what you tell them to do and show somewhat less than zero mercy if that's the wrong thing to do.

So given John Jacob Jingleheimer Schmidt

cin >> fullName; // reads John into fullname
getline(cin, fullName); // reads  Jacob Jingleheimer Schmidt into fullname, 
                        // replacing John
cout << fullName << endl; // prints  Jacob Jingleheimer Schmidt

Solution

Remove the cin >> fullName;

getline(cin, fullName); // reads John Jacob Jingleheimer Schmidt into fullname, 
cout << fullName << endl; // prints John Jacob Jingleheimer Schmidt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM