我尝试读取文件的第一行,但是当我尝试输入保存在文件中的文本时,它会打印出整个文件,而不仅仅是一行。该工具也不处理中断或空格。
我使用以下代码:
//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();
最佳答案
摆脱 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.
}
关于c++ - 如何从文件中只读取一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11140566/