I was reading K&R book and wanted to test out printf() and putchar() functions in ways that I never tried. I encountered several unexpected events and would like to hear from more experienced programmers why that happens.
char c;
while((c = getchar()) != EOF) {
//put char(c);
printf("%d your character was.\n", c);
}
- How would one get EOF (end of file) in the input stream (getchar() or scanf() functions)? Unexpected key that is not recognized by getchar()/scanf() function could produce it?
- In my book, it says that c has to be an integer, because it needs to store EOF and the variable has to be big enough to hold any possible char that EOF can hold. This doesn't make sense for me, because EOF is a constant integer with a value of -1, which even char can store. Can anyone clarify what was meant by this?
- What happens when I send "hello" or 'hello' to putchar() function? It expects to get an integer, but returns weird output, such as EE or oo, if I send the latter string or char sequence.
- Why when I use printf() function that is written above I get two outputs? One is the one I entered and the other one is integer, which in ASCII is end of line. Does it produce the second output, because I press enter, which it assumes to be the second character?
Thanks.
EOFusually is "-1",getchar()returns it whenread()from terminal returns 0. You can't usecharforgetcharbecause then in case of printing character with code 255 (for example, 'Ъ' in KOI8-R) you'll get a falseEOF. To hide input characters you should properly setup your terminal (turn off echo). - Eddy_EmEOF, you mean that the character is an integer larger than 1 byte and can be recognized by getchar(), if the variable's range is set to be more than 1 byte? - Jonas Hoffmann'hello'is not a valid string, it possibly results in undefined behaviour. Something between''must only represent a single character. - Bernhard BarkerEOFneed 2 bytes if it's -1? What characters can a person input to make the application think that it'sEOF? - Jonas Hoffmann