2012-08-09 233 views
0

我想傳遞一個fstream對象並標記這些單詞。它會一直打印無法打開文件hasNextToken()。願有人幫助我。fstream文件無法讀取

//main.cpp

int main() { 
    string filename = "input.txt"; 
    fstream inputStream(filename); 
    Tokenizer t(inputStream); 
    while (t.hasNextToken()) { 
    cout << t.nextToken(); 
} 
} 

//Tokenizer.h

class Tokenizer { 
    fstream fin; 

public: 
    Tokenizer(fstream& file) 
    { 
     fin << file; 
    } 

    bool hasNextToken() { 
     if (!fin) { 
      cout << "Could not open file: " << endl; 
      exit(0); 
     } 
     return true; 
    } 

    string nextToken() { 
     string line; 
     getline(fin, line); 
     if (fin) { 
      istringstream sin(line); 
      string word; 
      sin >> word; 
      return word; 

     } 
    } 
}; 
+0

錯誤信息? – 2012-08-09 05:12:00

+1

'fin'永遠不會被初始化。 – 2012-08-09 05:12:19

+0

我將它添加到初始化程序列表中,但出現有關訪問在ios中聲明的私有成員的錯誤。 – newbieLinuxCpp 2012-08-09 05:24:19

回答

1

試試這個:

class Tokenizer { 
    fstream& fin; 

public: 
    Tokenizer(fstream& file) 
    : fin(file) 
    {} 

... 
} 
+0

如果我這樣做,我得到這個錯誤:\ fstream(1347):錯誤C2248:'std :: basic_ios <_Elem,_Traits> :: basic_ios':無法訪問類中聲明的私人成員'std :: basic_ios <_Elem,_Traits >' – newbieLinuxCpp 2012-08-09 05:20:52

+0

這看起來像是你錯過了從'fstream fin'到'fstream & fin;'的變化。 – Axel 2012-08-09 05:29:06

+0

謝謝,現在它打印出文本文件的內容,但帶有額外的垃圾。 – newbieLinuxCpp 2012-08-09 05:59:55

0

我不知道這是否會工作,我可以現在不用測試,但你可以快速完成:

int main() { 
    string filename = "input.txt"; 
    fstream inputStream(filename, ios::in); // add second argument 
    // other stuff here 
} 

乾杯