getline不要求输入?

Uzu*_*Dev 5 c++ cin getline

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

问题是当被问及how much is that jacket?getline没有要求用户输入时,只输入初始值"0".为什么是这样?

Ben*_*ley 12

你必须混合时要小心operator>>使用getline.问题是,当您使用时operator>>,用户输入他们的数据,然后按Enter键,将换行符放入输入缓冲区.由于operator>>是以空格分隔,因此换行符不会放入变量中,而是保留在输入缓冲区中.然后,当你打电话时getline,换行符就是它唯一要找的东西.因为这是缓冲区中的第一件事,它会立即找到它正在寻找的内容,而不需要提示用户.

修复:如果您在getline使用后打算打电话operator>>,请在中间调用ignore,或者做其他事情来摆脱那个换行符,也许是一个虚拟调用getline.

另一种选择,就像马丁所说的那样,根本就是不使用operator>>,只使用getline,然后将你的字符串转换为你需要的任何数据类型.这会产生副作用,使您的代码更安全,更健壮.我会先写一个这样的函数:

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;
    */
}
Run Code Online (Sandbox Code Playgroud)

您可以为浮点数,双精度数和其他内容创建类似的函数.然后当你需要int而不是这个:

cin >> i;
Run Code Online (Sandbox Code Playgroud)

你做这个:

i = getInt(cin);
Run Code Online (Sandbox Code Playgroud)