In case of unknown number of integers to be read, we could use EOF to tell C program the end of input.

In linux system, we can use Control-D to initiate EOF, while in windows system, we use Control-Z to initiate EOF, when input from keyboard.

For example,

#include<stdio.h>

int main()
{
	int num;
        int count = 0;
	int total = 0;
	
	while(scanf("%d", &num) != EOF)
        {
		total = total + num; 
                count++;
	}
	printf("%d integers read,the total = %d\n", count, total);
	return 0;
}

stdin

12
23
34
45
56
^D//indicate a keyboard input Ctrl-D in linux or Ctrl-Z in windows

stdout

5 integers read,the total = 170

You have no rights to post comments