I'm trying to parse an input file line by line. I want to grab each line one at a time, put it into a null terminated char array. I can't seem to do it.

I tried something like this and just got weird ass results.

    int q = 0;
    do
    {
        //if(buffer[i] == )
        testFile >> buffer;
        q++;
    }
    while(buffer[q-1] != '\0');

    for(int i = 0; i < 80; i++)
    {
         cout << buffer[i];
    }

The buffer is 80 characters and the input file is a test file containing Dorothy Parker's short poem resume'
The code above will put the last word of line 2 into the array and stop there (rest the other 70 odd chars is just junk)I have no clue why. I was under the impression that when the code would encounter a new line it would stop. Does anyone have any suggestions. Please note, I'm not just trying to solve the problem, but also understand what is going on with the code above. Also the input file is 8 lines long.

For fun here's the out put:

damp;  p ♠> ╠√" ◄8@ |:> Σⁿ" ♦☺      x☺>     └5╠o*<├w     ♥☺♥    ⌠√"   @♠> ╨;>

where damp; is the only line from the inputfile.

Just call getline() which will do all that for you.

ifstream in("filename.txt");
char buf[80];
while( in.getline(buf,sizeof(buf)) )
{
   // do something
   cout << buf << '\n';
}

THANK YOU! I had tried getline(), but had the syntax all weird. So helpful! Thanks!

Also, are there '\n' s in input text files that one can test for? I'm still not understanding the funky results of my earlier code, and why it wasn't working.

Yes, the text files normally include '\n' as a line separator. Here's one way to do it one character at a time. I didn't compile or test this code, so I hope it doesn't contain any errors.

char line[80] = {0};
char ch;
int counter = 0
while( infile >> ch ) // read the entire file
{
   if( ch != '\n' && counter < sizeof(line) )
       line[counter++] = ch;
   else
   {
    line[counter] = '\0'; // null terminate the string
    cout << line << '\n'; // display the line
    counter = 0; // get ready for next line
  }
}
// last line of the file
line[counter] = '\0'; // null terminate the string
cout << line << '\n'; // display the line
counter = 0; // get ready for next line
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.