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;
 

 cout<<"please enter the first interger..."<<endl;

 do
 {
  cin>>val;
  if(!cin)
  {
	  cin.clear();
	  cin.ignore(100);
	  cout<<"please enter an interger"<<endl;
  }
  else
  {
  sum+= val;
  n++;
  cout<<"please enter another interger..."<<endl;
  
  }
  }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);
	  cout<<"please enter an interger"<<endl;
          continue;
  }
  else
  {
      sum+= val;
      n++;
      cout<<"please enter another interger..."<<endl;
  }
}

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!
think about ASCII CODE;)

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

 cout<<"please enter the first interger..."<<endl;

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

  }
  else
  {
  sum+= val;
  ++n;
  cout<<"please enter another interger..."<<endl;
  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!
think about ASCII CODE;)


Huh? ASCII has nothing to do with adding up some numbers.

Now, there is the case that the computed average will only be the integer value, as sum and n are both integers. This can be fixed by changing sum to a double, or typecasting one of the operands in the division to double.

if user inputs char the ascii would be different from integers!so by checking the ascii the program will come to know whether the input is char or not!!
btw I didn't say ASCII has to do with adding numbers:S,I meant for checking the input!

If the user enters some character that's not part of an integer, input halts at that point. It is not the case that if I hit 'a' on the keyboard that the ASCII value of 'a' will stored to the int variable val.

thanks:)I'm a new programmer.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.