流不能按预期工作 [英] Streams dont work as expected

查看:44
本文介绍了流不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题,需要快速解决.这是我的代码:

I have this problem and need really fast solving. It's my code:

    void stypendium() {
        string tresc = "";
        string temp;
        stringstream ss;
        fstream file;
        vector<float> grades;
        float grade, sum, av;
        file.open(this->plik, ios_base::in);
        if(!file.is_open()) {
            ofstream fileTmp(this->plik);
            fileTmp.close();
            file.open(this->plik, ios_base::in);
        }
        while (file >> temp) {
            if(strspn( temp.c_str(), "-.0123456789" ) == temp.size()) {
                ss.str("");
                ss << temp;
                ss >> grade;
                grades.push_back(grade);
            }
        };
        sum = 0;
        for(int i=0;i<grades.size();++i) {
            sum += grades[i];
        }
        av = sum / grades.size();
        cout << sum << "/" << grades.size() << "=" << av;
        file.close();
    }

};

问题在于在线

ss <<温度;

ss << temp;


没有任何东西进入流,尽管临时值有值;


nothing gets to the stream, though the temp has value;

推荐答案

使用 ss.clear() 成员函数为第一个和后续成绩值正确准备字符串流.这是参考:std::basic_ios::clear.请记住,clear() 可能会引发异常.

Use the ss.clear() member function to properly prepare the stringstream for the first and successive grade values. Here is the reference: std::basic_ios::clear. Keep in mind that clear() can throw an exception.


基于最近的源代码编辑,while 循环体与之前几乎相同.


Based on the most recent source code edit, the while loop body is nearly the same as before.

 while (file >> temp) {
     if(strspn( temp.c_str(), "-.0123456789" ) == temp.size()) {
         ss.str("");
         //
         // Call the clear() member function here
         //
         ss.clear(); 
         ss << temp;
         ss >> grade;
         grades.push_back(grade);
     }
 };

一个简单的测试文件,逐行具有等级值,每行获取一次,并且最后一个输入文件等级值仅添加到等级向量一次.

A simple test file having grade values on a line by line basis, has each line is obtained a single time, as well as the last input file grade value being added to the grades vector only once.

这篇关于流不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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