Почему TellP () дает -1? - PullRequest
       6

Почему TellP () дает -1?

1 голос
/ 22 февраля 2020

Я пытаюсь узнать о fstream, и вот код, который я запускаю на VS2019:

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

int main() {
    //cout << "lOOKING IN FILE";
    string s;
    fstream dictionary("C:/Users/source/repos/Test2/Test2/Text.txt");
    if (!dictionary) // were there any errors on opening? 
        exit(-1);
    while (dictionary >> s) cout << s << '\n'; // Print all names in file
    dictionary.seekp(0, ios::beg); // Go back to beginning of file
    cout << dictionary.tellp() << endl; 
    dictionary >> s;
    cout << s; // Print the first name
    return 0;
}

Вывод:

abc
acb
cab
-1
cab

Почему tellp дать -1, а не go началу файла?

1 Ответ

3 голосов
/ 22 февраля 2020

Вам необходимо очистить состояние потока.

Как только состояние потока изменилось с good (т.е. когда он достигает конца файла или есть сбой), тогда вы не сможете снова работать с потоком без очистки состояния.

...