getline不要求input?

这可能是一个非常简单的问题,但请原谅我,因为我是新的。 这是我的代码:

#include <iostream> #include <string> #include <sstream> using namespace std; int main () { string name; int i; string mystr; float price = 0; cout << "Hello World!" << endl; cout << "What is your name? "; cin >> name; cout << "Hello " << name << endl; cout << "How old are you? "; cin >> i; cout << "Wow " << i << endl; cout << "How much is that jacket? "; getline (cin,mystr); stringstream(mystr) >> price; cout << price << endl; system("pause"); return 0; } 

问题是,当被问到how much is that jacket? getline不会要求用户input,只需input初始值“0”。 为什么是这样?

混合operator>>getline时必须小心。 问题是,当你使用operator>> ,用户input他们的数据,然后按下回车键,在input缓冲区中放入换行符。 由于operator>>是空格分隔的,所以换行符不会放入variables中,而是保留在input缓冲区中。 然后,当你打电话给getline ,一个换行符就是它唯一要找的东西。 因为这是缓冲区中的第一件事,所以它会立即find它正在查找的内容,而不需要提示用户。

修复:如果打算在使用operator>>之后调用getline ,请在两者之间调用ignore,或者执行其他操作来清除该换行符,也许是对getline的虚拟调用。

另一种select是,马丁所说的是根本不使用operator>> ,只使用getline ,然后将string转换为所需的任何数据types。 这有一个副作用,使您的代码更加安全可靠。 我会先写一个这样的函数:

 int getInt(std::istream & is) { std::string input; std::getline(is,input); // C++11 version return stoi(input); // throws on failure // C++98 version /* std::istringstream iss(input); int i; if (!(iss >> i)) { // handle error somehow } return i; */ } 

你可以创build一个浮动,双打和其他东西类似的function。 那么当你需要int时,而不是这个:

 cin >> i; 

你做这个:

 i = getInt(cin); 

在到达换行符之前,忽略一些字符。

 cin.ignore(256, '\n') getline (cin,mystr); 

这是因为你在前一个调用的inputstream上有一个'\n'

 cin >> i; // This reads the number but the '\n' you hit after the number // is still on the input. 

进行交互式用户input的最简单的方法是确保每行都是独立处理的(因为用户在每次提示后都会进入)。

因此总是读一行,然后处理这一行(直到熟悉这些stream)。

 std::string line; std::getline(std::cin, line); std::stringstream linestream(line); // Now processes linestream. std::string garbage; lienstream >> i >> garbage; // You may want to check for garbage after the number. if (!garbage.empty()) { std::cout << "Error\n"; }