c++ - 为什么 istream.clear() 在读取 double 和字符串时删除了我的部分字符串?

标签 c++ cin istream

我正在阅读一个包含姓名和成绩的文本文件,格式为:

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

我使用以下代码将每个学生读入 Student_info 结构:

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

稍后我打印了每个学生的姓名和总成绩,但奇怪的事情发生了。而不是得到

Polly 96.6
Abraham 82.2

第一个 (Polly) 之后的每个名字都被部分截断了:

Polly 96.6
raham 82.2

我相信这与清除流以便为下一个学生做好准备有关:

in.clear();

好像是把下一个学生名字的开头丢掉了,但是我不能就这么去掉这一行,因为istream需要回到OK状态。

我怎样才能完成这项任务,同时确保我不会丢掉每个学生名字的一部分? (我假设我可能事先不知道有多少家庭作业,所以我不能简单地阅读 6 个 double 然后继续。)

最佳答案

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

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

关于c++ - 为什么 istream.clear() 在读取 double 和字符串时删除了我的部分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26580400/

相关文章:

c++ - 运行 while 循环直到收到特定输入,但如果没有收到 c++ 则重新运行

c++ - 跳过 std::istream 中的行

C++ istream operator >>

c++ - 死循环 -> 需要用Qt显示主屏幕

c++ - cin.fail 错误处理问题

c++ - C++ 中 EOF 的无限循环

c++ - istream_iterator 不进行零初始化

c++ - 将顶点坐标转换为 "same"屏幕坐标

c++ - Qt:按下按钮时显示多个窗口

c++ - 如何将字符串保存到 C++ 中类的 string* 成员?