2014-04-17 46 views
0

我想寫一個getline函數,將從一個打開的流中的字符串...我已經看過不同的網站,並試圖說它做什麼,但我越來越噸奇怪的錯誤。我需要使用getline來獲取文件「內容」部分中的所有單詞。這是我嘗試過的,但是我得到這個錯誤。在類C++中的Getline

// Fill a single Tweet from a stream (open file) 
// Returns true if able to read a tweet; false if end of file is encountered 
// Assumes that each line in the file is correct (no partial tweets) 
bool Tweet::FillTweet(ifstream &Din) 
{ 
    string tmp; 

    bool Success = false; 
    Din >> tmp; 
    if (!Din.eof()) 
    { 
     Success = true; 
     date = tmp; 
     Din >> hashtag >> getline(Din,contents); 
    } 
    else 
     cout << "I don't want to read your tweet anyway. " << endl; 

回答

1

這是不正確的使用方法getline()。更改爲:

Din >> hashtag; 
getline(Din,contents); 

爲什麼? getline()返回對istream的引用。有沒有超載>>運營商,它有兩個istream小號

+0

非常感謝! – savannaalexis

1

Din >> hashtag >> getline(Din,contents); 

需求是:

Din >> hashtag; 
    getline(Din, contents); 

我還要做

if (Din >> tmp) 

,而不是if (!Din.eof)

+0

你能解釋爲什麼你會改變(!Din.eof)嗎? – savannaalexis

+0

因爲你正在避免額外的檢查 - 如果'日期'不能被讀取但它不是EOF,你將不會得到一個無限循環。 (雖然這不太可能與字符串,當然) –

+1

[因此](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong)。檢查你的io,而不是假設他們是正確的,總是*一個好主意。 – WhozCraig