Pregunta

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;
}
¿Fue útil?

Solución

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top