0

Can someone explain this line a bit for me, I get the big picture, but the under-the-hood aspects are eluding me.

testFile.getline(buffer, sizeof(buffer));

I have a char array buffer of size 80. Get line extracts a line from my testFile, and puts it into the buffer. When I "cout" the buffer it only prints the line I grabbed, but if I scroll through the entire buffer I get all the junk at the end. I guess what I'm asking is, does getline slap a '\0' at the end of the chars it extracts from the file? Is this why "cout" doesn't spew all the garbage from the unused elements in the char array?

with the following code:

    testFile.getline(buffer, sizeof(buffer));
    int a = 0;

    while(buffer != '\0')
    {
        cout << buffer[a];
        a++;
    }

This prints the line it grabbed and just keeps a rolling spewing seemingly every ascii char known to man, over and over beeping and a booping ad-infinatum. I don't get it.

Edited by mixelplik

3
Contributors
5
Replies
21
Views
3 Years
Discussion Span
Last Post by Ancient Dragon
0

In the loop on lines 4-8, where is buffer incremented? line 4 always looks at the same character, which is why it's an infinite loop, unless buffer[0] == '\0'

Try this loop

while(buffer[a] != '\0')
    {
        cout << buffer[a];
        a++ ;
    }

Edited by Ancient Dragon

0

My C++ is a bit rusty, but I think that it may be because you are comparing a character array to a character. Which means that it will point to the first position in the array (I think). Line 4 should probably be

while(buffer[a] != '\0')

Edited by cgeier: comment added

0

I went ahead and accepted the fact that they were two incaptible types.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.