c++ – Problem in reprocessing the ifstream object

Question:

In the following code, the second loop never goes through Xcode, but it works as expected in Visual Studio:

int temp; char symbol;
std::ifstream ifs("a.txt");
while (ifs>>temp) cout<<temp<<' '; // перебор последовательности, как чисел.
cout<<endl;

ifs.seekg(0,ios::beg); // установка курсора в начало файла.
ifs.clear(); // очищение флага состояния.

while (ifs.get(symbol)) // перебор последовательности, как символов.
    if (symbol!=' ' && symbol!='\n') cout<<symbol<<' ';
ifs.close();

The second loop never goes through when the end of the file is reached in the first loop. All tests performed indicate a problem with the status flags. But the status flags after the 'clear ()' method are cleared as they should. Therefore, I cannot figure out this problem. Unsubscribe, please, those who encountered this problem?

Answer:

The difference is the std::istream::seekg in c++11 :

The function clears the eofbit flag, if set before the call.

The function clears the eof flag if it was set before the call.

and in c++98 :

If the eofbit flag is set before the call, the function fails (sets failbit and returns).

If the eof flag was set before the call, the function is executed with an error ( failbit set).

Those. if compiled with c++11 support, then seekg will seekg fine if they were already at the end of the file. Otherwise, it will return an error. Accordingly, you just need to swap the seekg and clear calls to make it work in both cases.

Scroll to Top