作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在编写一些简单的代码,这些代码应该读取所有其他字符,并在随机文本文件中用“?”覆盖它们的相邻字符。例如。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 个流,istream
和 ostream
。
您需要同步这两个流的位置才能实现您想要的。我稍微修改了您的代码以表明我的意思。
#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/
我是一名优秀的程序员,十分优秀!