EOF LOOPS????

This code is from my book and I even tried it on visual studio; however, I don't understand what it does and how it works. It is an EOF loop, but im not understanding the concept. Can someone explain to me whats going on? having toughtime grasping this concept

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  //declare variable for sum
	int sum=0;

	//delcare variabel for number
	int number;

	
	cin>>number;

	while(cin)
	{
		sum=sum+number;
		cin>>number;
	
	}

	cout<<"sum=" << sum;
	_getch();
You have no file that you are reading from in this case. In the instance that you are showing, this loop will never end because the user will always be forced to enter an input before the end of the loop.

An End-of-file loop works by continuing to read data from a file until there is no more data to read.

In order to break this infinite loop, you need to create a sentinel value; a value that is beyond the reasonable scope for your project.

This can be done by making an if statement

1
2
if(number == SENTINEL VALUE)
    break;


http://www.cplusplus.com/reference/cstdio/feof/
Last edited on
It is an EOF loop, but im not understanding the concept.


It is not an "EOF" loop. It is a loop that will end whenever a number is not successfully extracted from the input stream.

For instance, the input "a\n" will cause the loop body to be entirely skipped and "sum=0" to be displayed.
Topic archived. No new replies allowed.