fstream I/O未读取/写入
fstream I/O not reading/writing
我没有从这段代码中得到任何输出,可能是由于一个无限循环(不过不要相信我的话)。我非常仔细地阅读我的书,但没有用。
我没有出现任何错误,但跑步时什么也没发生。
程序需要打开一个文件,逐个字符地更改其内容,并将其写入另一个文件(这是一个删节版本)。
class FileFilter
{
protected:
ofstream newFile;
ifstream myFile;
char ch;
public:
void doFilter(ifstream &myFile, ostream &newFile)
{
while (ch!= EOF)
{
myFile.get(ch);
this->transform(ch);
newFile.put(ch);
virtual char transform (char)
{
return 'x';
}
};
class Upper : public FileFilter
{
public:
char transform(char ch)
{
ch = toupper(ch);
return ch;
}
};
int main()
{
ifstream myFile;
ofstream newFile;
myFile.open("test.txt");
newFile.open("new.txt");
Upper u;
FileFilter *f1 = &u;
if (myFile.is_open())
{
while (!nyFile.eof())
{
f1->doFilter(myFile, newFile);
}
}
else
{
cout << "warning";
}
myFile.close();
return 0;
}
如果您发布了可编译的代码,将更容易提供帮助。:)
你说得对,这里有一个无限循环:
void doFilter(ifstream &myFile, ostream &newFile)
{
while (ch != EOF) // <--- ch will never equal EOF
{
myFile.get(ch); // <--- this overload of get() only sets the EOF bit on the stream
this->transform(ch);
newFile.put(ch);
}
}
因为流的CCD_ 1方法并没有在文件末尾将字符设置为EOF。您可以使用无参数版本来获得这种行为:ch = myFile.get();
否则,您应该像在main()中那样测试!myFile.eof()
。
此外,您实际上并没有使用ch
的转换值,因此此代码不会更改输出文件中的值。要么使transform()与引用一起工作,从而更改其参数,要么执行ch = this->transform(ch);
。
相关文章:
- 如何在C++中从文件中读取/写入多个对象
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- 用 C++20 的给定键读取/写入 std::multimap 的所有值?
- 从缓冲区读取/写入文件
- 如何运行外部程序,向其传递内存地址以读取/写入?
- C++11 原子<>:只能使用提供的方法读取/写入?
- 从QDataStream读取/写入QT
- 在Windows上读取/写入未格式化的SD卡
- 尝试读取/写入Graphviz DAG值的工作证明会导致segfault
- 在 c++ 中读取/写入文件
- 在 c++ 中向/从文件中读取写入变量
- 如何在 c++ 中读取/写入无符号数组到 ifstream/ostream?
- QTcpSocket 或 QSslSocket 是否会自动创建用于读取/写入的线程?
- 使用来自 C 的内存地址的 Julia 读取/写入结构数据
- C++ 如何使用相同的类和方法来读取/写入可变大小的数据
- 在 Cap'nProto 中读取/写入配置结构
- 在另一个线程中读取/写入信息
- 提升信息解析器在读取/写入 INFO 格式文件时删除所有注释
- 在常量引用获取器上读取写入互斥锁(使用 Qt)
- C 读取/写入两个不同的文件(需要帮助了解要使用的语法)