从流中读取格式化的输入后,std :: getline()读取错误的数据 [英] std::getline() reads wrong data after reading formatted input from stream

查看:98
本文介绍了从流中读取格式化的输入后,std :: getline()读取错误的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了一些其他问题,但是我对C ++太陌生了,不知道它们是否适用于这里的问题.

I looked at some other questions and I'm too newbish at C++ to know if they applied to my question here..

基本上,当显示名称"的输出时,如果输入全名,则仅显示第二个单词.以前,它甚至什么都没有,只是跳过了.我现在对看起来如此简单的东西感到困惑.谢谢.

Basically when show the output of "name", if I type in my full name it only shows the second word. Before, it wasn't even taking anything at all, it just skipped it. I'm confused at the moment for something so seemingly simple. THanks.

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

int main()
{
double money;
string name;
int age;

// Prompt for age and receive
cout<<"How old are you? ";
cin >> age;

// Prompt for money and receive
cout<<"How much money do you have?";
cin >> money >> endl;

// Prompt for name and receive
cout<<"What's your name?\n\n"<< endl;
getline(cin, name);

// Display all information to user
cout<<"Hello, "<< name <<".";
cout << "You are " << age << " years old";
cout<< " and have $" << money << ".\n";

system("PAUSE");
return 0;
}

推荐答案

这是因为您有多少钱?"中的newline答复仍在输入缓冲区中.通常,将项目输入和基于行的输入(无论使用C和scanf/fgets还是C ++ >>getline)混合在一起不是一个好主意,因为您会遇到这类问题.

That's because the newline from the "How much money do you have?" reply is still in the input buffer. In general it is not a good idea to mix item input and line-based input (whether using C and scanf/fgets or C++ >> and getline), because you get these sort of problems.

您可以通过在getline之前的某个位置之前使用char dummy = cin.get();来解决这种特殊情况,但是,每次从项目输入"切换为行输入"时,都必须执行此操作,并且以后要更改顺序,您必须记住将cin.get()一起移动.

You can fix this particular situation by using char dummy = cin.get(); before somewhere before getline, however, you have to do that every time you switch from "item input" to "line input", and if you later change the order, you have to remember to move the cin.get() along.

一个更好的解决方案是始终使用基于行的输入,然后使用stringstream从字符串中获取数据,因此是这样的:

A better solution is to ALWAYS use line-based input, and then use stringstream to get the data out of the string, so something like this:

string ageString;
getline(cin, ageString);
stringstream ageSs(ageString);
if (!ageSs >> age)
{
    cout << "Bad input" << endl;
    exit(1);    // You may of course want to repeat rather than exit... 
}

这样,无论输入是什么,您都将读取整行.

That way, you are reading a whole line, no matter what the input is.

这篇关于从流中读取格式化的输入后,std :: getline()读取错误的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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