1

I have the following code:

    int data = 0;
    cout << "Enter a number: ";
    cin >> data;
    cout << "You entered " << data << endl;

    string str;
    cout << "Enter a string: ";
    getline(cin,str);
    cout << "Your entered " << str << endl;

After getting the first prompt, I entered a valid number 10. But as soon as I hit return, the program output:

You entered 10 Enter a string: Your entered

In other words, it didn't ask for the second string input. What happened?

Thanks

user2465355
  • 375
  • 1
  • 3
  • 15
  • 2
    Please use the search feature. There are [over 9000 duplicates](http://stackoverflow.com/search?q=%5Bc%2B%2B%5D%20getline%20skipping) of this. – chris Jun 09 '13 at 02:08

4 Answers4

4
std::cin >> data;

When you input the number for data, and hit the Return key to submit your input, a new line will be inserted into the stream. A new line is the default delimiter for the input stream, and when std::getline(std::cin, str) is used, the compiler will see that a new line is already in the stream, and it will stop running. To solve this, you need to ignore the offending character with std::cin.ignore:

std::cin.ignore();
std::getline(std::cin, str);
David G
  • 94,763
  • 41
  • 167
  • 253
1

Classic problem of mixing numbers and strings on input stream. Use getline for both and parse by using stringstream.

unxnut
  • 8,509
  • 3
  • 27
  • 41
0

Check out the below. The problem is that reading an integer does not read in the terminating newline. That newline is consumed when you use getline(...) and so your program exits. You need to consume that newline first.

int data = 0;
cout << "Enter a number: ";
cin >> data;
cout << "You entered " << data << endl;

string str;
cout << "Enter a string: ";
getline(cin,str); // consume endline <------------------
getline(cin,str);
cout << "Your entered " << str << endl;
zienkikk
  • 2,404
  • 1
  • 21
  • 28
0

When you enter 10, you're really entering "10\n", 10 plus the new line. It can depend on the OS, but basic idea of what is happening is that cin simply reads the 10 from the input buffer, and leaves the newline character. Then when your program reaches the getline part, getline reads the "\n" off the input buffer. Since "\n" is the default terminating character for getline, getline finishes and your programs keeps going.

So, at the end of your program, str contains simply "\n".

Nathan
  • 73,987
  • 14
  • 40
  • 69