fstream I/O未读取/写入

fstream I/O not reading/writing

本文关键字:读取 写入 fstream      更新时间:2023-10-16

我没有从这段代码中得到任何输出,可能是由于一个无限循环(不过不要相信我的话)。我非常仔细地阅读我的书,但没有用。

我没有出现任何错误,但跑步时什么也没发生。

程序需要打开一个文件,逐个字符地更改其内容,并将其写入另一个文件(这是一个删节版本)。

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);