cin正在跳过一条线

时间:2015-10-28 22:37:52

标签: c++ cin getline

以下是我正在处理的一段代码:

std::cout << "Enter title of book: ";
std::string title;
std::getline(std::cin, title);
std::cout << "Enter author's name: ";
std::string author;
std::getline(std::cin, author);
std::cout << "Enter publishing year: ";
int pub;
std::cin >> pub;
std::cout << "Enter number of copies: ";
int copies;
std::cin >> copies;

以下是此部分在运行时的输出(添加引号):

"Enter title of book: Enter author's name":

如何修复此问题以便输入标题?

2 个答案:

答案 0 :(得分:1)

我认为在你没有告诉我们之前你有一些意见。假设您这样做,可以使用std::cin.ignore()忽略std::cin中剩下的任何换行符。

  std::string myInput;
  std::cin >> myInput; // this is some input you never included.
  std::cin.ignore(); // this will ignore \n that std::cin >> myInput left if you pressed enter.

  std::cout << "Enter title of book: ";
  std::string title;
  std::getline(std::cin, title);
  std::cout << "Enter author's name: ";

现在应该可以了。

答案 1 :(得分:0)

getline是换行符分隔符。但是,使用类似std::cin的内容进行读取会在输入流中留下换行符。正如this建议的那样,当从分隔的空格切换到换行符分隔的输入时,您希望通过执行cin.ignore来清除输入流中的所有换行符:例如,cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');。 (当然,我假设您在将代码提取到MCVE中时,在cin之前遗漏了getline

相关问题