C++需要使用 .good 而不是 .eof

C++ need to use .good instead of .eof

本文关键字:eof good C++      更新时间:2023-10-16

可能的重复项:
为什么循环条件中的 iostream::eof 被认为是错误的?

是一个完全的初学者,我有这个功能,我在其中使用 .eof,但我被告知这不是一个好主意,因为这不适用于 linux,我应该使用 .good所以你能告诉我我会做什么以及我应该如何修改它吗

std::string ex_file_licensing::getUsedLicense(const std::string &FlexLMfileName){
        std::ofstream openFile;
        std::string line;
        std::string tempString;
        std::string testResult;
        size_t start_pos;
        size_t stop_pos;
        std::string retour ="";
        filebuf fb;
        fb.open (FlexLMfileName.c_str(),ios::in);
        istream toOpen(&fb);

        if(toOpen.eof()){
            while(!toOpen.eof()){
                getline(toOpen,line);
                if(line.find("Checkout") != std::string::npos ){   
                    start_pos = line.find(":"); 
                    tempString = line.substr(start_pos+1);
                    stop_pos = tempString.find("/");
                    testResult = tempString.substr(start_pos, stop_pos);
                }
                else if (line.find("FLEXnet") != std::string::npos ){   
                    start_pos = line.find("FLEXnet"); 
                    tempString = line.substr(start_pos+1); 
                    stop_pos = tempString.find("Feature");
                    testResult = tempString.substr(start_pos, stop_pos);
                }
                cout << testResult << endl;
                retour.append(testResult);
            }
            fb.close();
        }
        return retour;
    }

使用这样的循环:

while (getline(toOpen, line)) {
   ...
}

两者都不要使用:流有一个内置的布尔转换运算符,因此你可以简单地用if (toOpen)while(toOpen)来测试它,它就可以工作了。

顺便说一下,您的if条件看起来是错误的,因为它仅在文件流达到 EOF 字符时才执行其中的代码。