繁体   English   中英

如何只读取文件中的一行

[英]How to read only one line from a file

我试图读取文件的第一行,但是当我尝试将文本提供给保存在文件中的文本时,它会打印出整个文件,而不仅仅是一行。 该工具也不会照顾休息或空间。

我正在使用以下代码:

//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. }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM