【发布时间】:2014-10-07 02:06:15
【问题描述】:
我正在编写一些简单的代码,该代码应该读取所有其他字符,并在随机文本文件中用 '?' 覆盖它们的相邻字符。 例如。 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;
}
【问题讨论】:
-
保证您的第一个
if被占用;毕竟您的while条件完全相同(!data.eof())。 -
也许您在多个目录中有多个
test.txt? -
这里的问题是您没有考虑到您有 2 个流(
istream和ostream)。当指向istream的指针移动时,指向ostream的指针仍在旧位置。 -
data.eof()在这段代码中被使用了 3 次太多