为什么在读取双打和字符串时,istream.clear()删除部分字符串? [英] Why is istream.clear() removing part of my strings while reading doubles and strings?

查看:146
本文介绍了为什么在读取双打和字符串时,istream.clear()删除部分字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取一个文本文件,该文件由名称和等级组成,格式为:

I am reading a text file consisting of names and grades with the format:

Polly 95 99 95 94 93 98 99 
Abraham 80 85 81 86 95 78 81 

我使用以下代码阅读每个学生转换为Student_info结构:

I use the following code to read each student into a Student_info struct:

// read homework grades from an input stream into a vector<double>
istream& read_hw(istream& in, vector<double>& hw)
{
    if (in)
    {
        // get rid of previous content
        hw.clear();

        // read hw grades
        double grade;
        while (in >> grade) hw.push_back(grade);

        // clear the stream so that input will work for next student
        in.clear();

    }
    return in;
}

istream& read(istream& in, Student_info& s)
{
    // read and store the student's name, midterm, and final
    in >> s.name >> s.midterm >> s.final;
    //std::cout << "The name is " << s.name << std::endl;

    read_hw(in, s.homework);
    return in;
}

后来我打印了每个学生的姓名和总成绩,但还是有些奇怪。而不是得到

Later on I print each student's name and overall grade, but something strange happens. Instead of getting

Polly 96.6
Abraham 82.2

第一个(Polly)之后的每个名称都被部分切除:

each of the names after the first (Polly) is partially cut off:

Polly 96.6
raham 82.2

我相信这与清除流为下一个学生准备:

I believe it has something to do with clearing the stream to ready it for the next student:

in.clear();

这似乎扔掉了下一个学生名字的开头,但是我不能只是删除此行,因为istream需要返回到OK状态。

It seems to be throwing away the beginning of the next student's name, but I can't just get rid of this line, because the istream needs to return to an OK state.

我如何完成这项任务,但要确保我不会丢掉每个学生姓名的一部分? (我假设我可能事先不知道有多少作业,所以我不能简单地读6个双打然后继续前进。)

How can I accomplish this task but make sure I don't throw away part of each student's name? (I am assuming I may NOT know how many homework assignments there are beforehand, so I can't simply read 6 doubles and then move on.)

推荐答案


我如何完成此任务,但要确保不丢掉每个学生姓名的一部分?

How can I accomplish this task but make sure I don't throw away part of each student's name?



std::string line;
if (getline(in, line))
{
    std::istringstream iss(line);
    while (iss >> grade)
        hw.push_back(grade);
}

这是一种更加结构化的方法,要求在当前行中列出数字。

This is a more structured approach requiring the numbers be listed on the current line.

这篇关于为什么在读取双打和字符串时,istream.clear()删除部分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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