When I provide the input to the stream as "abcdefgh" and press enter key, it prints all the characters except the first one "a". Could anyone tell me why is this happening? Why isn't it reading all the characters in to the character array?
You while statement reads a character and checks it for end-of-file but then ignores the value read and the body of the while reads the next character in the stream! Note - this means you will print alternate characters and not as you say miss only the first one.
As far as reading characters into the array is concerned, you don't actually put them into the array so your array is not used.
Richard Tookey wrote:As far as reading characters into the array is concerned, you don't actually put them into the array so your array is not used.
Yes he does. On line 10. That also explains why he is only losing the first character and not alternative characters.
:-) Yep - my mistake! Since he reads a character in the while() I made the assumption he read a character at a time in the body of the loop. Silly of me. This does not change the fact that the character read in the while is discarded without being used.
Why this peculiar behavior? What magic happens when I explicitly assign the value returned by the read() method to an int primitive and then read it? What was preventing the earlier code from reading the first character?
Joined: Aug 05, 2005
Mansukhdeep Thind wrote:What was preventing the earlier code from reading the first character?
The earlier code was reading the first character, but because you didn't assign the read value to any variable it was discarded as soon as the comparison to -1 had been done. You then read all the remaining characters (or at least up to 1024 of them) into the array.
It's not peculiar behavior at all. Every time you call read() you consume 1 character from the stream. In your code you read the first char and compare it to -1. Then you read the remaining chars into the char array.
In the code provided by Joanne the value returned by read() is assigned to a char variable which is then compared to -1, so the while loop executes once for each char until the end of the stream is found. If you change your code to only read one char at a time inside the while loop you will see it only prints out every other char. This is because after reading the char and printing it out the while statement would execute again and read the next char and and execute the while loop until the end of stream is found. Of course if there is an odd number of chars in the stream the last print out will print the end of stream marker.