I'm pretty new at all this coding and trying to figure things out. I got this homework to do a calculator, and I have. With some issues (like forever loop if you put a letter instead of number, don't try it). Now I want to continue calculate with the result for those two numbers given. But I don't realy now where to start or if it's possible with the code I written. The task was just do do a simple calculator but I wan't to take it a step further, mostly for my own experience and learning.
Can anyone point me in the right direction?
Thanks. (Despite the username, I do learn well ;P )
its possible to keep the result, but you didn't!
each one of your 'case' statements might have:
result = nr1+nr2 //example for +
so that at the end you can say
nr1 = result; //move the answer into the first number
the get nr2 and loop back.
basically, a quick fix, move lines 15 and 16 above the while loop so it only happens once.
then stuff result into nr1 on line 44ish. Next time it loops it reads nr2 only and so on.
is this what you wanted?
most code uses double and rarely float. Use double unless you have a reason to use float instead, unlike integers, where you use the machine word sized (or straight up 'int') by default unless a reason to use another size.
#include <iostream>
int main() {
char choice {};
std::cout << "******Welcome to the calculator******\n";
do {
double nr1 {}, nr2 {}, result {};
char operat {};
bool bad {};
std::cout << "\nPlease enter a number you want to use: ";
std::cin >> nr1;
std::cout << "Now enter an Operator from +,-,*,/ you want to use: ";
std::cin >> operat;
std::cout << "And the other number you want to perform the action with: ";
std::cin >> nr2;
switch (operat) {
case'+':
result = nr1 + nr2;
break;
case'-':
result = nr1 - nr2;
break;
case'*':
result = nr1 * nr2;
break;
case'/':
result = nr1 / nr2;
break;
default:
std::cout << "Invalid operator\n";
bad = true;
}
if (!bad)
std::cout << nr1 << ' ' << operat << ' ' << nr2 << " = " << result << '\n';
std::cout << "\nDo you want to continue? Y/N: ";
std::cin >> choice;
} while (choice == 'Y' || choice == 'y');
std::cout << "\nThanks for using Calculator!\n";
}
put a letter instead of number
The issue here is that >> for a number expects a number and if it doesn't see one the stream extraction fails and the stream is set to fail mode. No more extraction can be done until the stream state has been reset to good and the 'bad' input removed from the input.
Thanks guys! You are genius. I have been out for a couple of days with Covid, horrible disease, but now I have taken my time to look over your answers and understand what you are writing. Those examples are badass, the last one especially. It is a way over my head but as I read I will learn more. And you made me understand a lot! This is fun and funnier it gets. Thanks again!