Hi, all
i have the assignment about program which reads in integers from cin until the user enters a non-integer (a character or EOF), then print out the average.
Its pretty simple assignment but i am kind of new.
So the following is my code and seems like have some problems.
So is there anybody could point out it?? Thanks

``````int main()
{
int val=0,n=0;
int ave;
long int sum=0;

do
{
cin>>val;
if(!cin)
{
cin.clear();
cin.ignore(100);
}
else
{
sum+= val;
n++;

}
}while(cin>>val);

ave = sum/n;
cout<<"the average is:"<<ave<<endl;

system("pause");
}``````
``````while(cin>>val)
{
//cin>>val;
if(cin.fail())
{
cin.clear();
cin.ignore(100);
continue;
}
else
{
sum+= val;
n++;
}
}``````

that is it..i guess..

Good guess, but not quite solving the problem
Both of your loops will keep you entering numbers forever

``````while( cin >> val )
{
if( cin.fail( ) )
{
//do nothing, we've reached the quit criteria
}
else
{
//do the summation and counter increment
}
}``````

The calculation is wrong!

``````#include<iostream>
using namespace std;
int main()
{
int val=0,n=0;
double ave;
long  sum=0;

do
{
cin>>val;
if(!cin)
{
cin.clear();
cin.ignore(100);

}
else
{
sum+= val;
++n;
cout<<"sum is in loop: "<<sum<<endl;
}
}while(cin>>val);

cout<<"sum is: "<<sum;
cout<<"n Is: "<<n<<endl;
ave = sum/n;
cout<<"the average is:"<<ave<<endl;

system("pause");
}``````

The calculation is wrong!