2013-02-14 22 views
6
ifstream infile; 

string read_file_name("test.txt"); 

infile.open(read_file_name); 

string sLine; 

    while (!infile.eof()) 
    { 
     getline(infile, sLine);   
     cout << sLine.data() << endl; 
    } 

    infile.close(); 

該程序打印文件中的所有行,但我只想打印第一行。如何從文件中讀取第一行?

+5

剛剛擺脫while循環和'而(infile.eof! ())'不正確 – billz 2013-02-14 04:44:49

+1

爲什麼你會期望一個循環只能通過一次(除非條件是這樣設置的)? – chris 2013-02-14 04:46:30

回答

10

while (!infile.eof())不工作您預期的那樣,​​看到一個有用link

輕微修正你的代碼,應該工作:

ifstream infile("test.txt"); 

    if (infile.good()) 
    { 
    string sLine; 
    getline(infile, sLine); 
    cout << sLine << endl; 
    } 

    infile.close(); 
+0

工作fine.thnx – user2036891 2013-02-14 04:59:35

0

你可以試試這個:

ifstream infile; 

string read_file_name("test.txt"); 

infile.open(read_file_name); 

string sLine; 

while (!infile.eof()) 
{ 
    infile >> sLine; 
    cout << sLine.data() << endl; 

} 

infile.close(); 

這應該由行打印所有行的文件,行。

相關問題