0

There's something wrong with my code. I typed something and pressed enter after seeing "the first string"on the screen but I saw a empty new line instead of "the second string". Then I typed something again and pressed enter again. Then I had no chance to enter the second string and got the output directly. I have tried cin.ignore() but it didn't work.

# include <iostream>
# include <string>

void main() {
    using namespace std;
    string str1;
    string str2;

    cout << "the first string" << endl;
    getline(cin,str1);
    cout << "the second string" << endl;
    getline(cin,str2);
    cout << str1 << endl << str2 << endl;
}
Simon
  • 1,616
  • 2
  • 17
  • 39
Kevin
  • 27
  • 5
  • It wouldn't compile for me because `void main()` must be `int main()`. Once I fixed that, it worked just fine. – Fred Larson Jan 27 '14 at 04:56
  • You'll get a compiler warning on most compilers for `void main()`, but the real issue is likely to be that you aren't checking to make sure the input stream is still valid, or that you aren't entering a line (that is you aren't pressing "ENTER" after your first input). [Example](http://ideone.com/B9mHmW) – Zac Howland Jan 27 '14 at 05:12
  • Hi Zac, I have tried your code but I still had to enter two lines for the first getline statement.But thank you. – Kevin Jan 27 '14 at 05:42
  • Hi Fred, I have changed void main()to int main() but it still didn't work. But Thank you . – Kevin Jan 27 '14 at 05:45
  • what do you mean by two lines? what compiler are you using? In Xcode (LLVM 5.0) I got http://ideone.com/0rBDRO, which is what I was expecting. – Gasim Jan 27 '14 at 07:41
  • Is this your entire program? Try doing `getline(cin >> ws, str1) ... getline(cin >> ws, str2)`. If that doesn't work try inputting Ctrl-D at the end of your input. – David G Jan 27 '14 at 14:17

1 Answers1

2

Try this version of flushing the input buffer. This may or may not be the solution in your case, but it is worth a try:

//code code code
cin.ignore( cin.rdbuf()->in_avail() );
getline(cin,str1);
cin.clear();
cin.ignore( cin.rdbuf()->in_avail() );
getline(cin,str2);
cin.clear();

//code code code
Jeff.Clark
  • 599
  • 1
  • 5
  • 27