0

Question

I am making some code notes for my friend in C++, and in one section, I have shown my friend three different ways of getting an input.

In my code, I have getline written on line 14, and cin written on line 18. So logically speaking, getline should be evaluated first, but it doesn't. Is this because getline is slower than cin? Could you also tell me how I can fix it?

I am fine if you mix up the format of the code, or add new code in whatever way you want, but don't delete any of the code already written to help me solve my problem.

Code

The first way is getting a number, the second way is getting a string, and the third way is getting multiple values.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int userInputedAge;
    cout << "Please enter your age: ";
    cin >> userInputedAge;

    string userInputedName;
    cout << "Please enter your name: ";
    getline(cin, userInputedName);

    int userInputedHeight, userInputedFriendsHeight;
    cout << "Please enter your height, and a friend's height: ";
    cin >> userInputedHeight >> userInputedFriendsHeight;
}

Here is the output.

Please enter your age: 13
Please enter your name: Please enter your height, and a friends height: 160
168

As you can see, I didn't have a chance to input my answer to Please enter your name: Why?

1 Answers1

0

This has nothing to do with evaluation order, and lines of code don't randomly switch places at runtime.

When you were prompted for an age, you entered a number, and then you hit enter. Granted, you did so for a good reason — it was the only way to signal to your terminal that it should send over what you've typed so far.

But that enter consists of an actual character (probably a newline, possibly a carriage return as well) which is still in the buffer. This causes the next input operation, a getline, to complete immediately. It has read an empty line.

Make your code skip that newline.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055