Link to home
Start Free TrialLog in
Avatar of dkim18
dkim18

asked on

Reading line from file and printing line

I am testing this file and cout<<line<<endl; doesn't print anything. After I excuete a.out, input.dat becomes empty file too!! Why is that?

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

int main()
{
     
   ifstream inFile("input.dat");
  string line;
  while (!inFile.eof())
  {
    getline(inFile, line);
    cout<<line<<endl;
  }
   return 0;
}
ASKER CERTIFIED SOLUTION
Avatar of bcladd
bcladd

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dkim18
dkim18

ASKER

Thank you pointing out my mistake.
hey! works perfectly!  are you going to award points to yourself?
getline can be a little screwy. getline keeps reading until it finds the \n char in a string of text, then it replaces the \n with a null ('\0') to create a string.

If the value of line is too small to read in the line requested then getline returns a junk string. (what I seem to remember anyway) , so the solution was to use a overly large value for line. Usually 80 chars is the max for most editing windows but wrap arround text can change that possibility. So use something like 200 or 300. That ensures that getline will find the \n (newline).

RJ
RJ -

There are two different getline functions. One, defined as part of istream, behaves exactly as you describe. It has the signature (simplified istream type for clarity)

std::istream &  std::istream::getline(char * buffer, unsigned int length, char delimiter = '\n');

This version reads into a fixed size buffer and, as you say, is prone to buffer overrun problems

The version used in the program fragment above is the other version of getline, the one defined along with std::string:

std::istream & getline(std::istream & in, std::string buffer, char delimter = '\n');

This version reads into a standard string which grows dynamically to accomodate the input stream.

Hope this is clear enough,
-bcl