How to use the End-Of-File (EOF) in C program to signal the stop of reading from standard input

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: Using the End-Of-File (EOF) which is Ctrl+C for PC to stop the reading from standard input

To show: How to use the End-Of-File (EOF) in C program to stop reading from the standard input

 

// Read from standard input, keyboard to standard output, console

// using pre defined functions getchar() and putchar() with End Of File (EOF).

// EOF is system dependent

#include <stdio.h>

 

int main(void)

{

int count;

 

// give some prompt...

printf("Enter a line of text:\n");

printf("EOF to stop.\n");

 

// get character from standard input store in variable count

count = getchar();

 

// while the End Of File is not encountered...

while(count != EOF)

{

// put character on the standard output

putchar(count);

// carry on getting character from the standard input

count = getchar();

}

return 0;

}

 

Output example:

 

Enter a line of text:

EOF to stop.

This is a line of text

This is a line of text

Use EOF to stop the input & output

Use EOF to stop the input & output

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index