i am trying to make a program with a loop that asks the user to input numbers until he/she presses q. Once the q key is pressed the program is supposed to calculate the average of all the numbers. When the user presses q however it just starts outputting "enter a number" an infinite amount of times. If anyone could help i'd be very appreciative
code:
#include <iostream>
using namespace std;
int main()
{
double num = 0, sum = 0, count = 0, avg;
cout << "Enter 'q' to stop entering numbers and calculate average" << endl;
cout << "Enter a number" << endl;
cin >> num;
sum = sum + num;
count = count + 1;
while(cin != 'q')
{
cout << "Enter a number: " << endl;
cin >> num;
sum = sum + num;
count = count + 1;
}
cout << endl;
cout << "Sum: " << sum << endl;
cout << "Count: " << count << endl;
avg = sum / count;
cout << "Average: " << avg << endl;
return 0;
}
There are numerous ways to approach this. One possibility is to use cin.peek() to take an advance look at the next character before deciding what to do. Another, which I show below, is to read the input as a string. Then, test the contents of the string to decide what to do. I've used a stringstream to extract the number from the string. There are other ways to convert the value, for example the function std::stod().
@Chervil i actually like your program a lot better but in the class i am in i am only allowed to use the <iostream> stuff. Is there a way to fix it with just that? Is it just a stupid issue I'm overlooking or much harder than that?
@chervil yes i am trying to do steps 1 and 3 in one thing. The idea is that they either enter a number to continue the loop or they enter q which cancels the loop and calculates the average. Sorry i was a little unclear. I'll try to use the Thomas loop. Thanks so much!
#include <iostream>
int main()
{
double sum = 0 ; // sum of all the numbers entered so far
int count = 0 ; // count of how many numbers were entered so far
double next_number ; // the next number entered by the user
char next_char ; // the next non white space character n the input buffer
std::cout << "Enter 'q' to stop entering numbers and calculate average\n" ;
while( std::cout << "next number? " && // prompt the user for the next number
// read in the next character; if it is 'q', end the loop; otherwise put it back
// into the input buffer so that we can try to read it in as part of the next number
std::cin >> next_char && next_char != 'q' && std::cin.putback(next_char) &&
std::cin >> next_number ) // try to read in the next number
{
sum += next_number ;
++count ;
}
if( next_char != 'q' ) std::cout << "*** error: unexpected input (not a number and not 'q')\n" ;
elseif( count > 0 ) std::cout << "average: " << sum / count << '\n' ;
}