fstream I / O不读/写

时间:2015-10-30 02:42:57

标签: c++ io polymorphism fstream

我没有得到此代码的输出,可能是由于无限循环(尽管不要接受我的话)。我非常密切地关注了我的书,但没有用。

我没有错误,但是当我跑步时没有任何反应。

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

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

1 个答案:

答案 0 :(得分: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);
  }
}

因为流的get()方法未在文件结尾处将字符设置为EOF。您可以使用无参数版本来获取该行为:ch = myFile.get();

否则,您应该像在main()中一样测试!myFile.eof()

此外,您实际上并未使用ch的转换值,因此此代码不会更改输出文件中的值。使transform()与引用一起使用,以便改变其参数,或者ch = this->transform(ch);

相关问题