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.