[英]Why does tellp() give -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
而不是去文件的開頭?
您需要清除流的狀態。
一旦流的狀態從good
狀態改變(即當它到達文件末尾或出現故障時),那么您不能在不清除狀態的情況下再次對流進行操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.