Below is the program that I wrote.
/*******************************************************************************
* This program reads EOF from standard input stream to store in an integer
* variable and in a character variable. Both values are then output to see the
* stored value as integer.
*******************************************************************************/
#include<stdio.h>
int main (void)
{
/* Local Declarations */
int num;
char ch;
/* Read EOF as character & integer and display values stored */
printf("\nPlease only input EOF for all input prompts below");
printf("\nNumber? ");
scanf("%d", &num);
printf("\nThat integer input converts to %d", num);
printf("\nCharacter? ");
scanf(" %c", &ch);
printf("\nThat character input converts to %d", ch);
/* Check if any of the stored values are recognized as EOF */
if(num == EOF)
printf("\nNumber is an EOF");
if(ch == EOF)
printf("\nCharacter is an EOF");
/* Exit Program */
printf("\n");
return 0;
}// main()
I compiled using gcc on Ubuntu 11.10. It does not recognize Ctrl-D for EOF in the program and outputs 0 when trying to print its value. The output for the above program on my terminal is below.
Please only input EOF for all input prompts below
Number?
That integer input converts to 0
Character?
That character input converts to 0
NOTE: CTRL-D is not echoed by the terminal when I press it for the two inputs, hence not visible in the above program execution.
I have read that EOF is defined as an integer in stdio.h and stdlib.h and is traditionally defined as -1. Also, I understand that Ctrl-D simulates EOF for standard input. Then why does it not translate to -1 when storing it to an integer variable?
fflushand have the\nat the end ofprintfformat strings! - Basile Starynkevitch\nat the end ofprintfformat strings rather than beginning? I have seen this convention in the book I am using to learn C and found it a bit odd. - Harsh Vardhanprintfare flushing the output buffer on\nnewline characters. So your book is wrong in that aspect, you really should take the habit of putting it at the end of your format strings. And this is what most Linux utilities (e.g. shells,make, orgccitself) are doing. - Basile Starynkevitchsetlinebuffunction. On Linux (and probably on Posix systems), when stdout is a terminal, it usually is line buffered. - Basile Starynkevitch