getline不要求输入? [英] getline not asking for input?

查看:155
本文介绍了getline不要求输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is probably a very simple problem but forgive me as I am new. Here is my code:

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

问题是,当问这件夹克多少钱? getline不要求用户输入,只输入初始值0。为什么是这样?

The problem is that when asked "how much is that jacket?" getline does not ask the user for input and just inputs the initial value of "0". Why is this?

推荐答案

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

You have to be careful when mixing operator>> with getline. The problem is, when you use operator>>, the user enters their data, then presses the enter key, which puts a newline character into the input buffer. Since operator>> is whitespace delimited, the newline character is not put into the variable, and it stays in the input buffer. Then, when you call getline, a newline character is the only thing it's looking for. Since that's the first thing in the buffer, it finds what it's looking for right away, and never needs to prompt the user.

修复:
如果'在使用 operator>> 后调用 getline ,在其间调用忽略,删除换行符,也许是 getline 的虚拟调用。

Fix: If you're going to call getline after you use operator>>, call ignore in between, or do something else to get rid of that newline character, perhaps a dummy call to getline.

另一种选择,马丁说的是不使用 operator>> ,只使用 getline 将字符串转换为您需要的任何数据类型。这有一个副作用,使您的代码更安全和健壮。我将首先编写一个这样的函数:

Another option, and this is along the lines of what Martin was talking about, is to not use operator>> at all, and only use getline, then convert your strings to whatever datatype you need. This has a side effect of making your code more safe and robust. I would first write a function like this:

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,而不是这样:

You can create a similar function for floats, doubles and other things. Then when you need in int, instead of this:

cin >> i;

您这样做:

i = getInt(cin);

这篇关于getline不要求输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆