mercredi 30 novembre 2016

Reading in a new line after cin>> doesn't work

I have problems processing a newline read from stdin:

#include <iostream>
#include <string>
...

using namespace std;

int main() {

    ...

    unsigned int maxelems;

    cout << "Maximal number of elems that can be taken in one move: ";

    if (!(cin >> maxelems)) {

        cout << "Bye!" << endl;
        exit 1;
  }

  string pl1_str;

  cin.ignore();

  cout << "Player 1 (hu=human, ra=random, opt=optimal):" << endl;

  if (!(getline(cin, pl1_str))) {

      cout << "Bye1!" << endl; return 1;

  }

  if(pl1_str =="hu")
        //do smth
    else if(pl1_str =="ra")
        //do smth
    else if(pl1_str=="opt")
       //do smth
    else {
        cout << pl1_str << "Bye2!" << endl; exit 1;
    }

    ...
}

When I run this, the cin on maxelems and the flushing with cin.ignore() works.

When I get to:

Player 1 (hu=human, ra=random, opt=optimal):

and I enter:

hu<Enter>

The end of line seems not to be reached. When I press Enter again:

hu<Enter><Enter>

the application ends with "Bye1!" which is not what I want.

Now if I insert another cin.ignore():

...
cout << "Player 1 (hu=human, ra=random, opt=optimal):" << endl;
cin.ignore();
...

and I enter:

hu<Enter>

the line is processed, but the application terminates with:

u Bye2!

Ok, cin.ignore() cuts of the "h" , but why is the line suddenly processed? How can I assign "hu" to pl1_str?

Aucun commentaire:

Enregistrer un commentaire