在程序中不能得到正确的输出

Cant get correct output in program

本文关键字:输出 程序 不能      更新时间:2023-10-16
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
    fstream file("file.txt");
    file << "this is new line" << endl;
    file.flush();
    string c;
    file >> c;
    cout << c << endl;
    file.close();
}

当我运行这个输出是空的,如果我删除行file << "this is new line" << endl;我得到正确的输出,为什么?

通过写入文件,您将内部文件指针移动到文件的末尾。这意味着下次读取时,您将位于文件的末尾,因此不会读取任何内容。

seek()移动文件指针