Why is istream.clear() removing part of my strings while reading doubles and strings?

一曲冷凌霜 提交于 2020-01-24 23:58:08

问题


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 

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

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();

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.

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.)


回答1:


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.



来源:https://stackoverflow.com/questions/26580400/why-is-istream-clear-removing-part-of-my-strings-while-reading-doubles-and-str

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!