user2097237
user2097237

Reputation: 11

Multiple string store in different variable C++

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.

Upvotes: 1

Views: 899

Answers (1)

ipc
ipc

Reputation: 8143

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.

Upvotes: 3

Related Questions