Hupfauer
Hupfauer

Reputation: 591

How to read only one line from a file

I tried to read the first line of a file, but when I tried to give to text, which was saved in the file, it prints out the whole file, not only one line. The tool is also not looking after breaks or spaces.

I'm using the following code:

//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();

Upvotes: 2

Views: 11444

Answers (1)

Robᵩ
Robᵩ

Reputation: 168596

Get rid of your while loop. Replace this:

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

Wit this:

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


EDIT: Responding to the new requirement "that it read a line wich i can define in second variable ?"

For that, you'll need to loop, reading each line in turn, until you've read the line you care about:

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

Upvotes: 2

Related Questions