user2036891
user2036891

Reputation: 231

How can i read first line from file?

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

This program prints all line in the file, but I want to print only first line.

Upvotes: 10

Views: 69873

Answers (2)

billz
billz

Reputation: 45450

while (!infile.eof()) does not work as you expected, eof see one useful link

Minor fix to your code, should work:

  ifstream infile("test.txt");

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

Upvotes: 20

Dkrtemp
Dkrtemp

Reputation: 23

You can try this:

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

This should print all the lines in your file, line by line.

Upvotes: 2

Related Questions