2015-10-30 102 views
0

我沒有從這段代碼輸出,可能是由於無限循環(不要聽我說)。我非常密切地關注着我的書,但無濟於事。fstream I/O不能讀取/寫入

我沒有得到任何錯誤,但是我跑步時沒有任何反應。

該程序需要打開一個文件,逐個字符地更改它的內容,並將它們寫入不同的文件(這是一個刪節版本)。

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

是nyFile一個錯字? –

+0

看起來你在FileFilter類中也缺少一對大括號。 –

+0

我想知道爲什麼你需要在過濾器函數之外的while循環,因爲你在過濾器函數內部有while循環,反之亦然。 –

回答

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