gpt4 book ai didi

C++ 文件 I/O——不能同时读/写?

转载 作者:搜寻专家 更新时间:2023-10-31 01:42:48 24 4
gpt4 key购买 nike

我正在编写一些简单的代码,这些代码应该读取所​​有其他字符,并在随机文本文件中用“?”覆盖它们的相邻字符。例如。test.txt 包含“Hello World”;运行程序后,它会是“H?l?o?W?r?d”

下面的代码允许我在控制台窗口中读取文本文件中的所有其他字符,但是程序结束后,当我打开 test.txt 时,没有任何改变。需要帮助找出原因...

#include<iostream>
#include<fstream>
using namespace std;

int main()
{

fstream data("test.txt", ios::in | ios::out); //here the test.txt can be any random text file
while (!data.eof())
{
if (!data.eof())
{
char ch;
data.get(ch);
cout << "ch is now " << ch << endl;

}


if (!data.eof())
data.put('?');

}
data.close();
return 0;
}

最佳答案

您忘记考虑您有 2 个流,istreamostream

您需要同步这两个流的位置才能实现您想要的。我稍微修改了您的代码以表明我的意思。

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
char ch;
fstream data("test.txt", ios::in | ios::out); //here the test.txt can be any random text file
while (data.get(ch))
{
cout << "ch is now " << ch << endl;
data.seekg(data.tellp()); //set ostream to point to the new location that istream set
data.put('?');
data.seekp(data.tellg()); //set istream to point to the new location that ostream set
}
data.close(); // not required, as it's part of `fstream::~fstream()`
return 0; // not required, as 0 is returned by default
}

关于C++ 文件 I/O——不能同时读/写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26227564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com