在使用 ofstream 变量向文件添加一些信息后,为什么我无法将数据从文件写入字符串?

Why I can't write data from a file to a string, after I added some information to file using an ofstream variable?

I am trying to write and read information from the same file, but I don't know actually how to do that and why it doesn't work.

When I compile the code, the string that I expect to be filled with information from the file, actually doesn't get filled.

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

using namespace std;


int main()
{
    string str;
    ifstream fin("Asort.txt");
    ofstream fout("Asort.txt");

    fout << "hello world";  

    getline(fin, str);
    cout << str;
}

问题是语句后 "cursor"(因此:标记)的位置:

fout << "hello world";

插图:

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

using namespace std;


int main()
{
    string str;
    ifstream fin("Asort.txt");
    ofstream fout("Asort.txt");

    fout << "hello world";  //output to cout this statement(fout.tellp()) to see where the marker is at this point in the stream
    fout.seekp(0);   //reset the marker in the fout stream to the beginning
    getline(fin, str);
    cout << str;
}

光标现在位于流的末尾。所以你必须使用: fout.seekp(0); 让它到达开头,以便 fin 可以从流的开头开始读取。