c++输入与输出流操作与文件操作

2025-05-05 18:41:35
推荐回答(1个)
回答1:

#include
#include
#include
#include

int main()
{
using namespace std;
string str;

ofstream fout("exampli.txt");
if (!fout)
{
cerr << "写入 exampli.txt 文件失败。\n";
exit(EXIT_FAILURE);
}
while (getline(cin, str) && str != "")
{
fout << str << endl;
}
fout.close();

ifstream fin("exampli.txt");
if (!fin)
{
cerr << "打开 exampli.txt 文件失败。\n";
exit(EXIT_FAILURE);
}
while (!fin.eof())
{
getline(fin, str);
cout << str << endl;
}
fin.close();
return 0;
}