繁体   English   中英

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

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

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


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM