Thanks Michael. I took me really long time to realize that I needed two
integers (an extra int tmp). So it really works now.
I just don't really understand why it works...
OK, think of "stdin" as coming from a file, rather than from the
keyboard. (It works the same either way, except that when reading
from the keyboard, the "contents" cannot be predicted in advance
by peeking at the file. You would have to peek at the typist's
mind instead.)
If a file consists in its entirety of a pair of lines like this:
abcdefg
wxyz
then the contents of the stream, taken one character at a time, are:
'a', 'b', 'c', 'd', 'e', 'f', 'g', '\n', 'w', 'x', 'y', 'z', '\n'
after which a subsequent attempt to read will encounter the EOF
condition, which getc(stream) will represent by returning the special
EOF value (typically -1).
Suppose we edit the file with a "binary editor" and remove the last
line, but also remove the newline that comes after the first line.
Then getc() will return:
'a', 'b', 'c', 'd', 'e', 'f', 'g', EOF
Let's look at my code (int charInput, tmp
do
{
printf("\nWrite to result.txt (y/n)? ");
charInput = getchar();
do {
tmp = getchar();
} while(EOF != tmp && '\n' != tmp); // */
}
while (charInput != 'y' && charInput != 'n');
Here, charInput will get the 'a', leaving 'b' thorugh 'g' in the
stream. Then the loop using "tmp" will get the 'b', then 'c', then
'd', ..., then 'g', then EOF. Since EOF == EOF, the loop will stop
at this point, with tmp==EOF.
What happens if we replace the input file with one that contains the
character sequence '\n', 'y', '\n' (then EOF)?
I did a little debugging and it seems like charInput always contains the
first character I enter, while tmp always contains "10" which AFAIR is \n.
It is on most systems.
Shouldn't the while line be changed to: } while(EOF != tmp || '\n' !=
tmp);? I mean: tmp can't be EOF and \n at the same time, can it?
Indeed, it cannot be equal to both EOF (a negative integer) and '\n'
(a positive integer). What happens if you ask whether, for instance:
if (EOF != EOF || EOF != '\n')
?
I tried Ctrl+D on mac os x. Isn't that EOF?
It is set-able, but that is the default. However, depending on the
C library, you may sometimes have to type it more than once. The
C standard allows, but in C89 at least does not require, EOF to be
"sticky": if a stream encounters EOF, the C library can stop asking
the underlying OS for more input until you call clearerr() on the
stream. On the other hand, the C library can go ahead and keep
asking for more input anyway. Different systems do different things
here.