【问题标题】:getline not asking for input? [duplicate]getline不要求输入? [复制]
【发布时间】:2011-10-02 08:10:19
【问题描述】:

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

#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 并不要求用户输入,而只是输入初始值“0”。这是为什么呢?

【问题讨论】:

标签: c++ getline cin


【解决方案1】:

operator&gt;&gt;getline 混合时必须小心。问题是,当您使用operator&gt;&gt; 时,用户输入他们的数据,然后按下回车键,这会将换行符放入输入缓冲区。由于operator&gt;&gt; 是用空格分隔的,因此换行符不会放入变量中,而是保留在输入缓冲区中。然后,当您调用getline 时,它只需要换行符。由于这是缓冲区中的第一件事,因此它会立即找到要查找的内容,而无需提示用户。

修复: 如果您要在使用 operator&gt;&gt; 后调用 getline,请在两者之间调用 ignore,或者执行其他操作来删除该换行符,也许是对 getline 的虚拟调用。

另一个选项,这与 Martin 所说的一致,就是根本不使用 operator&gt;&gt;,而只使用 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;
    */
}

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

cin >> i;

你这样做:

i = getInt(cin);

【讨论】:

  • 非常感谢本杰明!我完全理解你
  • 我为什么不早点加入这个网站:-/
  • “return stoi(input)”是否基本上意味着如果返回类型是字符串转换为整数?
  • @Kyle:不。意思是“返回 stoi(input) 的返回值”。 stoi 取一个字符串(这里不涉及if,必须是字符串,否则编译不通过),并尝试将其转换为整数。
【解决方案2】:

这是因为您有一个 '\n' 留在上次调用的输入流中。

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

进行交互式用户输入的最简单方法是确保独立处理每一行(因为用户将在每次提示后按回车键)。

因此总是读取一行,然后处理该行(直到您熟悉流)。

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";
}

【讨论】:

  • 我不明白?那么你到底建议我做什么来让 getline 请求输入呢?对不起,我是一个完整的 n00b
  • 谢谢你们,一旦我明白我在做什么,我会记住这一点......干杯
【解决方案3】:

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

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

【讨论】:

  • 您能再解释一下吗?为什么我忽略 256 个字符不超过一个字节,那么为什么是 256 个?
  • 这是从输入流中提取或忽略的最大个字符。根据输入的长度,您可以有一个大于 256 的数字。在您的情况下,我假设 256 是 name 字符串的最大输入字符长度。
猜你喜欢
  • 2012-11-12
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
  • 2015-12-14
  • 2018-03-24
  • 2016-02-05
相关资源
最近更新 更多