2015-11-08 116 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