I'm working on a program which is supposed to read a series of numbers from the user and calculate the mean and range. When there is no input, it is supposed to print that there is no input and end the program. I am having issues getting this last part (if there is no input) to happen. Here's what I have so far:
/* Write a program which reads a series of numbers from the user and
then prints the mean and the range.
To stop entering numbers, press control-z. All numbers must be between 0 and 100.
*/
#include <iostream>
usingnamespace std;
int main()
{
double n;
double minval = 0;
double maxval = 0;
double count = 0;
double sum = 0;
double range;
//I don't have to tell the user to enter an integer or to press ctrl-Z when finished.
while(cin >> n) //This part of the program works perfectly.
{
if(n < 0 || n > 100)
{
cout << "out of range; ignored" << endl;
continue;
}
++count;
sum += n;
if (count == 1)
{
maxval = n;
minval = n;
}
if (n > maxval)
{
maxval = n;
}
if (n < minval)
{
minval = n;
}
range = maxval - minval;
}
//This is where the problem occurs!
while !(cin==n) //This is coming up as an error
{
cout << "No data was entered." << endl;
break; /* I want to break the program after the above cout if the
there is no user input for n */
}
// Again, this cout part works too.
cout << "The average is " << sum/count << endl;
cout << "The range is " << range << endl;
}
Well, this makes no sense... why a while loop? Why are you trying to compare the input stream object with n? What is the ! doing after the while?
You return from a function with return. When you return from main, the program terminates.
1 2 3 4 5
if (count==0)
{
cout << "No data was entered." << endl;
return 0;
}