多次调用时,c ++ getline()不等待来自控制台的输入

use*_*852 21 c++ getline

我试图从控制台获取一些用户输入参数,两个字符串,两个整数和一个double.我试图使用的相关代码是:

#include <string>
#include <iostream>
using namespace std;

// ...

string inputString;
unsigned int inputUInt;
double inputDouble;

// ...

cout << "Title: "; 
getline(cin, inputString);
tempDVD.setTitle(inputString);

cout << "Category: "; 
getline(cin, inputString);
tempDVD.setCategory(inputString);

cout << "Duration (minutes): "; 
cin >> inputUInt; 
tempDVD.setDuration(inputUInt);

cout << "Year: "; 
cin >> inputUInt; 
tempDVD.setYear(inputUInt);

cout << "Price: $"; 
cin >> inputDouble; 
tempDVD.setPrice(inputDouble);
Run Code Online (Sandbox Code Playgroud)

但是,在运行程序时,代码不会等待输入第一个inputString,而是在第二次getline()调用之前代码不会停止.因此控制台输出如下所示:

标题:类别:

光标出现在类别之后.如果我现在输入,程序然后跳转到年份输入,不允许我输入多个字符串.这里发生了什么事?

Mar*_*ork 20

问题是你使用运算符>>混合调用getline().

请记住,operator >>忽略了前导空格,因此将正确地跨行边界继续.但是在成功检索到输入后停止读取,因此不会吞下尾随'\n'字符.因此,如果你在>>之后使用getline(),你通常会得到错误的东西,除非你小心(首先删除未读取的'\n'字符).

诀窍是不使用这两种类型的输入.选择合适的一个并坚持下去.

如果它是所有数字(或者与运算符一致的对象>>)那么只需使用运算符>>(注意字符串是唯一与输入/输出不对称的基本类型(即不能很好地运行)).

如果输入包含字符串或需要getline()的东西的组合,那么只使用getline()并解析字符串中的数字.

std::getline(std::cin, line);
std::stringstream  linestream(line);

int  value;
linestream >> value;

// Or if you have boost:
std::getline(std::cin, line);
int  value = boost::lexical_cast<int>(line);
Run Code Online (Sandbox Code Playgroud)


Mar*_*say 14

您需要刷新输入缓冲区.它可以完成cin.clear(); cin.sync();.

  • 对我来说,奇怪的是,将它们结合使用是行不通的。它仅适用于`std :: cin.ignore()`。 (4认同)

Rik*_*ika 10

您可以使用

cin.ignore();
Run Code Online (Sandbox Code Playgroud)

或者@kernald提到使用

cin.clear();
cin.sync();
Run Code Online (Sandbox Code Playgroud)

在使用getline之前()