dimanche 17 juin 2018

C++ Input Stream cin [duplicate]

This question already has an answer here:

I am practicing input stream in C++, and I come across a problem while running a while loop in C++.

Here is my program

#include <string>
#include <iostream>
#include <fstream>

using namespace std;
int main()
{
    string input;

    do {
        cout << "? ";
        getline(cin, input);
        if (input == "a")
        {
            string entry;
            cin >> entry;
            cout << entry << endl;
        }

    } while (input != "q");

    system("pause");
    return 0;
}

Output

? a
hello <- this is what I type
hello <- print out what I typed
? ? <- Error?

I simply do not understand how come the while loop executed twice after I input a string. I know the problem is due to the cin but I do not know how to solve it. Thank you!

Aucun commentaire:

Enregistrer un commentaire