2015-11-08 91 views
0

我正在製作一個程序,您可以在其中登錄和註冊。所有的數據都存儲在一個.txt文件中。我現在遇到的問題是,當我試圖從文件中獲取所有數據時,我只能得到文件的第一行/字符串。我想讓.txt中的所有內容。下面是一些代碼:C++從.txt中讀取所有內容

是什麼在.TXT:

hello:world 
foo:bar 
usr:pass 

代碼(作爲測試):

ifstream check; 
check.open("UsrInfo.txt"); 

string dataStr; 
getline(check, dataStr); 

cout << dataStr; 
cout << endl; 

輸出:

hello:world 

我想要的輸出成爲:

hello:world 
foo:bar 
usr:pass 

我能做些什麼來解決這個問題?謝謝!

+0

的可能的複製[逐行讀取文件中的行(http://stackoverflow.com/questions/7868936/read-file-line-by-line) – soon

+1

'我只得到了第一line'有你考慮重複其他行相同的操作? [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)可能有幫助。 – Drop

回答

5

您需要通過線把它通過一個循環,並讀取線

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

    int main() { 
    string line; 
    ifstream check ("example.txt"); 
    if (check.is_open()) 
    { 
     while (getline (check,line)) 
     { 
     cout << line << '\n'; 
     } 
     check.close(); 
    } 

    else cout << "Unable to open file"; 

    return 0; 
    } 
-2

函數getline得到一個行,如果你想了解更多,然後一行試試這個;

std::string Line, Result; 
while (true){ 
    getline(check, Line); 
    if (!check.eof()) 
    Result.append(Line), Result.push_back('\n'); 
    else 
    break; 
} 
+0

[雖然不eof幾乎從來沒有工作](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong)並不會在這裏。逗號運算符幾乎肯定不是你想在這裏使用的。應該可以工作,但是由於逗號濫用的方式太多,不值得教導或模仿的編碼風格非常糟糕,可能會沉默地阻止程序。只需使用分號。 – user4581301

+0

你認爲這會解決嗎? – user4578093

+1

建議'while(getline(check,Line))'而不是'while(true)'。 'getline'返回對所使用的iostream的引用,並且iostream實現一個布爾運算符,如果流可讀且不處於錯誤狀態,則返回true。 'Result.append(Line),Result.push_back('\ n');'從''中沒有任何收穫。爲了清晰起見,使用';'或'Result.append(Line +「\ n」);' – user4581301