2010-01-21 85 views
0

我正在嘗試編寫一個遞歸函數,該函數會在爲類分配打開的文件中執行一些格式化操作。這是我迄今爲止寫的:從C++中的文件中讀取

const char * const FILENAME = "test.rtf"; 

void OpenFile(const char *fileName, ifstream &inFile) { 
    inFile.open(FILENAME, ios_base::in); 
    if (!inFile.is_open()) { 
     cerr << "Could not open file " << fileName << "\n"; 
     exit(EXIT_FAILURE); 
    } 
    else { 
     cout << "File Open successful"; 
    } 
} 


int Reverse(ifstream &inFile) { 
    int myInput; 
    while (inFile != EOF) { 
     myInput = cin.get(); 
    } 
} 

int main(int argc, char *argv[]) { 
    ifstream inFile;    // create ifstream file object 
    OpenFile(FILENAME, inFile); // open file, FILENAME, with ifstream inFile object 
    Reverse(inFile);   // reverse lines according to output using infile object 
    inFile.close(); 
} 

我的問題是在我的Reverse()函數中。我是如何從文件中一次讀取一個字符的?謝謝。

回答

0
void Reverse(ifstream &inFile) { 
    char myInput; 
    while (inFile.get(myInput)) { 
     // do something with myInput 
    } 
} 
1

你會更好使用這樣的:

char Reverse(ifstream &inFile) { 
    char myInput; 
    while (inFile >> myInput) { 
    ... 
    } 
} 

人們常常忽視的是,你可以簡單地測試是否輸入流已經只是測試的流對象EOF擊(或其他一些不好的狀態)。它隱含地轉換爲bool,而istreams運算符bool()只是調用(我相信)istream::good()

將此與流提取操作符始終返回流對象本身(以便它可以與多個提取進行鏈接,如「cin >> a >> b」)相結合,並且您到達非常簡潔語法:

while (stream >> var1 >> var2 /* ... >> varN */) { } 

UPDATE

對不起,我沒有想到 - 當然這將跳過空格,這不會爲你的倒車文件的內容的例子工作。最好在使用

char ch; 
while (inFile.get(ch)) { 

} 

也返回IStream對象,允許good()的隱式調用堅持。