为什么tellp()给出-1?

问题描述 投票:1回答:1

我正在尝试学习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而不转到文件的开头?

c++ visual-studio fstream
1个回答
2
投票

您需要clear流的状态。

© www.soinside.com 2019 - 2024. All rights reserved.