1

这是我第一次在这里发帖,所以我会尽量明确我的问题。所以我需要在变量中存储带有空格的不同字符串。我正在使用 eclipse,但我遇到了问题。

这是代码

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');

....

这就是控制台向我显示的内容

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

问题是我没有时间在第二个 cout 之前输入字符串“Theme”。我尝试了不同的方式,使用 char 缓冲区它不起作用我进入一个循环。

4

1 回答 1

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.

于 2013-02-21T21:49:05.700 回答