So I'm doing a simple sum code and the user has to enter '-1' in order to get the total sum, but whenever I enter -1, it just repeats "Would you like to enter another number?" again instead of giving me the sum.
#include "stdafx.h"
#include <iostream>
int main()
{
double temp = 0;
double sum = temp;
char question = 'n';
bool finished = false;
while (!finished)
{
std::cout << "Enter a number: " << std::endl;
std::cin >> temp;
sum += temp;
std::cout << "Would you like to enter another number? Enter Y to input another number or enter -1 to get your sum." << std::endl;
std::cin >> question;
if (question == '-1')
{
finished = true;
}
};
std::cout << "\nThe sum of numbers entered is: " << sum << std::endl;
//Pause Code
int pause;
std::cin >> pause;
return 0;
}
you declared "question" as a character. Maybe check if(question == 'n' || question == 'N') instead. Your current check doesn't make sense, since "-1" is two characters -- it's probably only comparing to "-".
There are a few things that need to be changed in your code to make it work correctly. To start with your char variable, you are assigning it 'n':
char question = 'n';
In the while loop's if statement you have:
if (question == '-1')
...
To make this work you would need an integer variable that you can then say:
if (question == -1)
finished = true;
Also you should 'prime read' an integer value, before asking for another in the while loop. This means:
1 2 3 4 5 6
std::cout << "Enter a number: " << std::endl;
std::cin >> temp;
sum += temp;
while(!finished)
....
Below is a working example. The only change is that the bool variable is deleted, a 'prime read' of a number has been introduced, and the while loop has been changed to a do-while loop.
#include <iostream>
#include <iomanip>
int main()
{
double temp = 0.0;
double sum = 0.0;
char question = ' ';
// Prime read a number
std::cout << "Enter a number: " << std::endl;
std::cin >> temp;
// Assign it to the sum variable
sum += temp;
do
{
// Ask for another number
std::cout << "Enter another number: " << std::endl;
std::cin >> temp;
sum += temp;
std::cout << "Would you like to enter another number? "
<< "Enter Y to input another number or enter 'N' to get your sum." << std::endl;
std::cin >> question;
// Introducing a check that a user only enters Y/N
while (toupper(question) != 'Y' && toupper(question) != 'N')
{
std::cout << "Would you like to enter another number? "
<< "Enter Y to input another number or enter 'N' to get your sum." << std::endl;
std::cin >> question;
}
} while(toupper(question) == 'Y');
// Output the values with 2 decimal places
std::cout << std::fixed << std::setprecision(2);
std::cout << "\nThe sum of numbers entered is: " << sum << std::endl;
//Pause Code
int pause;
std::cin >> pause;
return 0;
}