int main()
{
   string name;
   cout << "Please enter the filename of the encoded message:";
   getline(cin,name);

   ifstream infile;
   infile.open(name.c_str());

   if (infile.fail()) {
      cout << name << " fail to open." << endl;
      exit(1);
   }

cout << name << endl;
   cout << " File successfully opened" << endl;

   string buffer;
   getline(infile, buffer);

   while ( !infile.eof() ) {
   cout << buffer << endl;
   }

   return 0;
}

Hi I'm making a program where the user types in the name of a file and displays the context of the file in the console window. I'm trying to use getline function to read from the stream. The problem is that it reads the file and displays ONLY the first line ( it displays the first line, but it' an infinite loop) of the file to the console screen. How do I get it to display all the lines of the file to the terminal? I know I could use some type of loop, but I don't know what to do for the loop. So how do I display the other lines?

This is how you read a file using getline:

while ( getline ( infile, buffer ) ) {
  // Process the line
}

This is how you read a file using getline:

while ( getline ( infile, buffer ) ) {
  // Process the line
}

I don't understand that can u post it in my code?

I don't understand that can u post it in my code?

getline(infile, buffer);

   while ( !infile.eof() ) {
   cout << buffer << endl;
   }

This is an infinite loop. Put the getline statement inside the while loop. If you put it where Narue says to put it, you can get rid of the eof part.

while ( getline(infile, buffer) ) {
   cout << buffer << endl;
   }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.