1

This is my first time I post here so I'll try to be clear in my question. So I need to store different string with space in variable. I'm working with eclipse and I have a problem.

This is the code

using namespace std;
string p_theme;   
string p_titre;
int p_anneeEdition;
string p_pays;
string p_auteur;
string p_editeur;
string p_isbn;

cout << "Veuillez saisir le thème:" << endl;
getline(cin, p_theme, '\n');


cout << "Veuillez saisir le titre:" << endl;
getline(cin, p_titre, '\n');

....

This is what the console show to me

Veuillez saisir le thème:
Veuillez saisir le titre:

The problem is that I don't have the time to enter the string "Theme" before the second cout. I've tried different way, with a char buffer it didn't work i enter in a loop.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 2
    Welcome to SO. Your program should be a [short self-contained compilable example](http://sscce.org/), which makes things much easier. – Zeta Feb 21 '13 at 21:47
  • Answered here? http://stackoverflow.com/questions/7786994/c-getline-isnt-waiting-for-input-from-console-when-called-multiple-times – Nate Hekman Feb 21 '13 at 21:49
  • @Nate: The answer covers formatted _extraction on_ `cin` and `getline`. Here we use formatted _output_ on `cout`, which shouldn't have any effect on a `getline` call on `cin`. – Zeta Feb 21 '13 at 21:51
  • @Zeta: The answer covers `getline(cin, ...)` not waiting for user input, which seems to be exactly the problem reported here. I'm not sure which of us is misreading the question. – Nate Hekman Feb 21 '13 at 22:23

1 Answers1

3

A getline which does nothing can have many reasons

  • A failbit was set (because reading of an int or similar has failed) in which case all calls to read from cin get ignored.
  • You have unread chars remaining on the input buffer. For example "\n" (which can be if you read a std::string with operator>>).

To handle both cases, insert

cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n'); 

before each call of getline (and add #include <limits> at the top of your file).

This is surely an overkill and if you are careful, this can be reduced.

  • Check each input if it succeeds (like int i; if (std::cin >> i) { /* ok */ })
  • Don't read a std::string without getline (for example operator>>), unless you later call cin.ignore(...).

If you do all this, the code should work as you already have it.

ipc
  • 8,045
  • 29
  • 33
  • `cin.clear()`? Why do you want to clear the error flags? Your current answer suggests that `clear` might clear the stream to someone who doesn't know `istream`s, who might then be confused why you ignore other values. Please elaborate. – Zeta Feb 21 '13 at 21:55
  • @Zeta: I don't know the code before the `getline` in the posted question. Maybe a failbit was set (which would lead exactly to the behavior posted). If I would know the real code, not all of this is needed before every call of getline. – ipc Feb 21 '13 at 21:57