flag is not set when the last character has been read but when trying to read the next not available character. So you must check for
after reading a character and before printing it out.
Reading the character and checking for
can be done inside the while condition: