10
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.

billz
  • 44,644
  • 9
  • 83
  • 100
user2036891
  • 231
  • 3
  • 5
  • 11

2 Answers2

20

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;
  }
Zitrax
  • 19,036
  • 20
  • 88
  • 110
billz
  • 44,644
  • 9
  • 83
  • 100
2

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.

Dkrtemp
  • 23
  • 4