我尝试打开一个文件,在它上写一些东西,从文件中读取并再次执行相同的过程,但是输出不是我所期望的,下面是代码:
file.open("ciao.txt", std::ios::out);
file << "ciao";
file.close();
file.open("ciao.txt", std::ios::out | std::ios::in);
std::string str;
std::getline(file, str);
cout << str;
file.seekp(0);
file << "addio";
std::getline(file, str);
cout << str;预期的调幅是“交差”,但它只给了我“交友”。我试着逐行运行它,但是一旦程序停止,文件就会被编辑。有人能帮忙吗?我在网上找不到任何东西-;
发布于 2022-08-25 10:54:21
问题是事物的组合。
在这里,您可以将ciao写到文件中,没有问题--只是它没有换行符(\n)。
file << "ciao";稍后,你读了一句话:
std::getline(file, str);如果文件中有一个\n,就不会到达EOF,而且fstream仍然处于接受I/O的良好状态,但现在并非如此。
因此,要么在file.clear()之后添加getline,要么向第一个输出添加一个换行符:
file << "ciao\n";您还需要在上一次file.seekg(0);之前使用getline。
file.open("ciao.txt", std::ios::out);
file << "ciao";
file.close();
file.open("ciao.txt", std::ios::out | std::ios::in);
std::string str;
std::getline(file, str);
file.clear(); // add this
cout << str;
file.seekp(0);
file << "addio";
file.seekg(0); // add this
std::getline(file, str);
// I added > and < to make it clear what comes from the file:
cout << '>' << str << "<\n";输出:
ciao>addio<https://stackoverflow.com/questions/73486095
复制相似问题