C++ 同时读取和写入 2 个文本文件

C++ Reading and Writing 2 text files simultaneously

本文关键字:文本 文件 读取 C++      更新时间:2023-10-16

我可以写入文本文件并从文本文件中读取,但是如果我读取另一个文件,我无法保存已读取的内容并处理它!

ifstream in;
ofstream out;
in.open("text.in", fstream::in);
if (!in.is_open()) return -1;
out.open("text.out", fstream::out);
if (!out.is_open()) return -1;
string line;
getline(in, line);
cout << line << endl;
in.close();
out.close();
return 0;

通常上面的内容会打印出"text.in"文件中的第一行,但是如果我打开"text.out"文件,它不起作用!

如何同时打开两个文本文件?

谢谢!

那是因为您打印的不是out文件cout

cout << line << endl;

// Add (or replace) the above line
out << line << endl;