How can i read first line from file?

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;
  }

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.

Tags:

C++