character processing from a file

Dec 4, 2012 at 6:36pm
I'm simply trying to utilize the get and peek functions to process characters from a file. I'm sure there's a much more efficient way to do this but I just want to know why this wont work for me. I hit run, enter the file name but nothing happens. Doesn't the peek function check the next character without consuming it?

'ch' is a char, 'inFile' is an fstream object for input, 'in' is a string

1
2
3
4
5
6
7
8
9
10
11
12
 ch = inFile.peek();
    while (ch != EOF)
    {
        while(ch !='\n'){
        inFile >> in;
        cout << in << " ";
        ch = inFile.peek();
        }

        ch = inFile.peek();

    }


What comes out as output is:
Enter filename: sample.txt[Enter]

Nothing happens after that, and the program doesn't end. So it's in an infinite loop I think?
Dec 4, 2012 at 8:04pm
What does your sample.text file actually contain?

This code reads and outputs the words on the first line.

Then it encounters the '\n' character and enters an infinite loop, because, as you rightly said, "Doesn't the peek function check the next character without consuming it?"
Dec 6, 2012 at 10:01pm
My file could contain any text, but I guess to give you a sample text:

I walked my dog to the park.
My dog's name is Spot.

My program should output that in one line. Is the reason why i get an infinite loop is because the stream extraction operator and peek function never consume the new line character? What could I use then so the program will jump to the next line?
Dec 6, 2012 at 10:30pm
Thanks for the sample file contents. That's reasonable. (I just wondered in case there might be some unusual non-displayable characters there.)

Is the reason why i get an infinite loop is because the stream extraction operator and peek function never consume the new line character?

Yes. or at least the peek function doesn't consume it. The cin alone will ignore whitespace including newlines.

You could use inFile.get(); at line 10, instead of peek()
That should move the program past the '\n' character.

You might also find it useful to change line 2 to while (ch !='\n' && ch != EOF)
Last edited on Dec 6, 2012 at 10:47pm
Topic archived. No new replies allowed.