I'm writing a code where the user can input as many numbers as they want to be added together. Once they're done, they enter Q and the addition commences.
My problem is that I have an infinite loop. I've checked several other instances of infinite loops on this website and StackOverflow, but none of the advice seems to fit my situation. Here's the code:
#include <iostream>
usingnamespace std;
//Maria Jones (CS-215, 006)
int main()
{
int sum = 0; //The variable that holds the sum of all numbers entered
int ans; //The user's input
char exit = 'Q';
do
{
cout << "Enter a series of numbers, then type Q to process:" << endl;
cin >> ans;
}
while (ans != 'Q');
if (ans = cin.fail() )
{
sum = sum + ans;
cout << "The corresponding element for the cumulative total sequence is: " << sum << " ." << endl;
}
}
Now, when I press Q, the sentence "Enter a series of numbers, then press Q to process:" runs on forever and ever unless I exit out of the program. Also, my if statement doesn't show up at all! Does that also mean cin.fail is incorrect?
I'm in CS 215 and haven't taken CS 115 in a year. The teacher keeps saying that these are simple problems, but they don't look or feel simple at all!
I'm writing a code where the user can input as many numbers as they want to be added together. Once they're done, they enter Q and the addition commences.
ans is an int. You can't stuff a 'Q' into an int. Entering a 'Q' when trying to read an int will result in the stream you're extracting from going into an error state. So further attempts to read are ignored. Line 17 will always be true (unless the user happens to enter the ascii value for 'Q' as one of the series of numbers.)
If you want to just retrieve numbers until a non-number value is found:
1 2 3 4 5 6
cout << "Enter numbers\n> ";
while ( cin >> ans )
sum += ans;
cout << "The sum is: " << sum ".\n";