Streams dont work as expected

泪湿孤枕 提交于 2019-12-25 08:15:38

问题


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

};

Problem is that in line

ss << temp;


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


回答1:


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.


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.




回答2:


You also need to call ss.clear(); after doing ss.str("");.

The reason is that when the stringstream is extracting a float, if it reaches the end of the string before it has definitely finished reading a float then it will set the eof state on the stream. Then, since eof is set, future conversions fail. You have to clear() to reset the eof state.



来源:https://stackoverflow.com/questions/22933580/streams-dont-work-as-expected

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