2012-06-21 24 views
1

我试图读取文件的第一行,但是当我试图给文本时,它们保存在文件中,它打印出整个文件,不仅一行。该工具也是而不是照看休息或空间。如何从文件中只读取一行

我用下面的代码:

//Vocabel.dat wird eingelesen 
ifstream f;       // Datei-Handle 
string s; 

f.open("Vocabeln.dat", ios::in); // Öffne Datei aus Parameter 
while (!f.eof())     // Solange noch Daten vorliegen 
{ 
    getline(f, s);     // Lese eine Zeile 
    cout << s; 
} 

f.close();       // Datei wieder schließen 
getchar(); 
+4

我认为最少的编程知识是需要在这个网站.. – Griwes

+2

你想要一条线,但是你每次循环并得到一条线?如果你这样做,尽管如此, 'while(getline(f,s))'。 – chris

+0

一个有用的建议:C++是英文的,所以评论也应该用那种语言...... –

回答

2

摆脱你while循环。替换此:

while (!f.eof())     // Solange noch Daten vorliegen 
    { 
    getline(f, s);     // Lese eine Zeile 
    cout << s; 
    } 

威特此:

if(getline(f, s)) 
    cout << s; 


编辑:“它读取一行至极,我可以在第二个变量定义”应对新需求

对于这一点,你需要循环,读反过来每一行,直到你读行,你在乎:

// int the_line_I_care_about; // holds the line number you are searching for 
int current_line = 0;   // 0-based. First line is "0", second is "1", etc. 
while(std::getline(f,s))  // NEVER say 'f.eof()' as a loop condition 
{ 
    if(current_line == the_line_I_care_about) { 
    // We have reached our target line 
    std::cout << s;   // Display the target line 
    break;      // Exit loop so we only print ONE line, not many 
    } 
    current_line++;    // We haven't found our line yet, so repeat. 
} 
+0

所以任何人都有任何ideeas? –

+0

请参阅我的编辑。 –

+0

非常感谢你<3 –