2009-04-08 65 views
1

我想我可能需要使用一個布爾bValue = false爲我而條件:ifstream的object.eof()不工作

char cArray[ 100 ] = ""; 
ifstream object; 
cout << "Enter full path name: "; 
cin.getline(cArray, 100); 
if (!object) return -1 // Path is not valid? This statement executes why? 

ifstream object.open(cArray, 100); 

// read the contents of a text file until we hit eof. 
while (!object.eof()) 
{ 
// parse the file here 

} 

爲什麼我不能進入文本文件的全路徑名?

這可能是因爲eof。他們的語法是否可以模擬eof的布爾語句?

我可以有:

while (!object == true) 
{ 
// parase contents of file 
} 
+0

你沒有一個C++編譯器編譯這段代碼,除非你推翻錯誤莫名其妙。你是否從實際編譯的內容中重新輸入了它?也許你應該複製和粘貼你確實有問題的代碼。 – 2009-04-08 17:48:13

回答

-1

ifstream::open功能需要一個文件名和一個可選的模式。既然你想閱讀整個文件,爲什麼不開始在開始時:

ifstream obj(cArray); 
if (obj) { // file successfully opened for reading 
    while (obj.good()) { 
     // read in a line at a time 
     string line; 
     getline(line, obj); 
     if (!line.empty()) { // we have something to work with 
      // parse 
     } 
    } 
} 

當然,一個更光滑的版本是在while環路尼爾·巴特沃思來測試getline

+0

我想我只是無法讀取整個文件路徑..實際上可能甚至沒有問題的eof – user40120 2009-04-08 17:18:54

+0

@lampshade:檢查出你的緩衝區cArray是否足夠大的文件路徑。 – dirkgently 2009-04-08 17:23:18

+0

這真的不是一個好主意 - 即使getline不能讀取任何內容,也會調用「解析」 – 2009-04-08 17:26:20

7

請您和其他人注意,正確的讀取文本文件的方式不需要使用eof(),good(),bad()或者indifferent()函數(OK,我做了最後一個一個)。 C中也是如此(用fgets(),feof()等)。基本上,這些標誌只會在嘗試讀取某些東西后纔會設置,並帶有getline()之類的函數。測試讀取函數更加簡單,更可能是正確的,比如getline()直接讀取某些東西。

沒有測試 - 我升級我的編譯器:

#include <iostream> 
#include <fstream> 
#include <string> 
using namespacr std; 

imt main() { 

    string filename; 
    getline(cin, filename); 

    ifstream ifs(filename.c_str()); 
    if (! ifs.is_open()) { 
     // error 
    } 

    string line; 
    while(getline(ifs, line)) { 
     // do something with line 
    } 
} 
+0

我可以使用控制條件嗎?缺乏你的getline(ifs,line)? – user40120 2009-04-08 17:20:31

+0

我不明白「senteinal」的含義 – 2009-04-08 17:23:16

+0

http://en.wikipedia.org/wiki/Sentinel_value – 2009-04-08 17:58:25