【问题标题】:fstream I/O not reading/writingfstream I/O 不读/写
【发布时间】:2016-01-30 09:32:51
【问题描述】:

我没有从这段代码中得到任何输出,可能是由于无限循环(不过,不要相信我的话)。我非常密切地关注我的书,但无济于事。

我没有收到任何错误,但运行时没有任何反应。

程序需要打开一个文件,逐个字符更改其内容并将它们写入不同的文件(这是一个精简版)。

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

【问题讨论】:

  • 看起来您在 FileFilter 类中还缺少几个大括号。
  • 我想知道为什么您需要在过滤器函数之外使用 while 循环,因为您在过滤器函数中有 while 循环,反之亦然。
  • 应该也关闭新文件,不需要使用this->调用transform。但这一切都是偶然的。我看不出有什么是错的。
  • 你上面提到的额外循环是我唯一能想到的。是的,这些都是错别字。真的没有其他问题了吗?考虑到它不能正常工作,这太奇怪了。 @DominicMcDonnell
  • 关闭或不关闭文件有时会产生影响(取决于操作系统),试试 newFile.close();在末尾。也就是说,这极不可能。

标签: c++ io polymorphism fstream


【解决方案1】:

如果您发布可编译的代码,帮助会容易得多。 :)

你说得对,这里有一个无限循环:

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-&gt;transform(ch);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 2014-09-15
    • 2012-04-05
    • 1970-01-01
    • 2016-09-29
    相关资源
    最近更新 更多