C++ Troubleshooting my command line calculator - c++

I am using xcode for my c++. It is a simple command line calculator.
This is what I have so far:
//
// main.cpp
// test
//
// Created by Henry Bernard Margulies on 8/21/13.
// Copyright (c) 2013 Henry Bernard Margulies. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
int main()
{
bool loopy = true;
cout << "\nCalculator\n";
while (loopy == true)
{
bool gooy;
double answ; // answer
double fn; // first number
double sn; // second number
string opersym; // operation symbol
string oper; // operation
string more; // rerun the program or not
cout << endl << "Operation please (+, - , x or d): "; //Problem1
cin >> oper;
if (oper == "+") //makes sure operation is viable
{
gooy = true;
}
if (oper == "-")
{
gooy = true;
}
if (oper == "x")
{
gooy = true;
}
if (oper == "d")
{
gooy = true;
} //does the above
else
{
cout << endl << "Enter a real operation"; //complains if oper not viable
gooy = false;
continue;
}
if (gooy == true)
cout << endl << "First number please: ";
if(!(cin >> fn)) //makes sure it is a number
{
cerr << endl << "Enter a number next time, please try again"; //complaint
gooy = false;
loopy = true;
break; //Problem2
}
if (gooy == true)
{
cout << endl << "Next number: ";
if(!(cin >> sn))
{
cerr << endl << "Enter a number next time, please try again";
gooy = false;
loopy = true;
break; //Problem2
}
if (gooy == true)
{
opersym = oper;
if (oper == "+")
answ = fn + sn;
if (oper == "-")
answ = fn - sn;
if (oper == "x")
answ = fn * sn;
if (oper == "d")
{
opersym = "รท";
answ = fn / sn;
}
cout << endl << "You entered: " << fn << " " << opersym << " " << sn << ". And it equals " << answ;
cout << endl << "Want more? y/n: ";
cin >> more;
if (more == "n")
{
cout << endl << "Okay, I'm not wanted. Shutting down. :(";
return(0);
}
if (more == "y")
{
cout << endl << "Back to work!";
}
else
{
cout << endl << "Since you can not be bothered to type it right, I'll take it as a no. :(";
return(0);
}
}
}
}
return 0;
}
I have several requests:
First, only division seems to work. Check the first part of main where it asks for an operation and confirms it. It does not want to work for +, - or x, but only for d
2.Check the two comments named problem2. In these parts continue; and break; don't restart the calculator properly. I want to go back to the beginning of the while loop and goto is supposedly unstable and bad.
3.Could you correct my code? I am no expert and the whole thing is very dirtily done. Please show me better logic to make the code shorter, faster and more stable.
Thanks!
ps. I'm a 12 year old kid teaching myself c++ off the internet, so please cut me some slack and explain things like you're speaking to a puppy.

Your problem is the else after if (oper == "d") If the operation is not d, the else clause will activate, even if an operation was picked earlier. Try this instead.
if (oper == "+")
{
gooy = true;
}
else if (oper == "-")
{
gooy = true;
}
else if (oper == "x")
{
gooy = true;
}
else if (oper == "d")
{
gooy = true;
}
else
{
cout << endl << "Enter a real operation"; //complains if oper not viable
gooy = false;
continue;
}
Now the final else will only activate, if all previous else clauses were activated.
Alternatively
if (oper == "+" || oper == "-" || oper == "x" || oper == "d")
{
gooy = true;
}
else
{
cout << endl << "Enter a real operation"; //complains if oper not viable
gooy = false;
continue;
}
break exits the loop it is in. Try continue instead. It goes back to the top of the loop, and if the condition is true, starts over.
Try to declare variables closer to where they are used. For example answ and opersym are not used until late in the loop. You can declare them local to the if statement block for if (gooy == true)

first of all, good luck with learning C++. I am sure you'll pick it up in no time at all :) Here's a basic calculator. It's not ideal but shorter.
#include <iostream>
#include <string>
int main()
{
using namespace std; //use namespace only within the scope of main()
//ask user to choose operation
string operation = "";//good to initialize local variable. otherwise C++ assigns them garbage values
while(operation != "+" && operation != "-" && operation != "*" && operation != "/")
{
cout << "Please enter a mathematical operation. Options are: + or - or * or /" << endl;
cin >> operation;
}
cout << "You entered " << operation << endl << endl;
//ask user to enter two numbers
double number1 = 0, number2 = 0, result = 0;
bool success = false;//true if calculation carried out successfully
//keep looping till calculation carried out successfully
while(success!=true)
{
cout << "Please enter the first number: " << endl;
cin >> number1;
cout << "Please enter the second number: " << endl;
cin >> number2;
if(operation == "+") result = number1 + number2;
else if(operation == "-") result = number1 - number2;
else if(operation == "*") result = number1*number2;
else if(operation == "/" && number2 != 0) result = number1/number2;
else
{
cout << "Please enter non-zero value for number2 since carrying out division" << endl;
continue;
}
success = true;
cout << "Result is: " << number1 << " " << operation << " " << number2 << " = " << result << endl;
}
return(0);
}

Related

Can't figure out how to give user all the options for starting, stopping, and restarting program?

Ok so I am trying to build this random number teller which basically tells the users whether the number they input is less than, greater than, or equal to 50 and also give them the options to start, stop, and restart the "random number teller" Here is the code:
#include <iostream>
using namespace std;
main() {
cin >> boolalpha;
int invalid_answer {0};
const int const_num {50};
int random_num {};
char answer {};
int keep_going {};
while (keep_going == 0) {
while (invalid_answer == 0) {
//=======================================================================================================================================
cout << "Enter a random number and we will tell you if it is greater than or less than " << const_num << ": " << endl;
cin >> random_num;
if (random_num > const_num) {
cout << random_num << " is greater than " << const_num;
}
else if (random_num == const_num) {
cout << random_num << " is the same as " << const_num << endl;
}
else {
cout << random_num << " is less than " << const_num << endl;
}
cout << "Want to try again? Type \"Y\" or \"N\"";
cin >> answer;
//=======================================================================================================================================
if (answer == 'N') {
cout << "Ok then, sorry to see you miss out" << endl;
keep_going = 1;
}
//=======================================================================================================================================
while(answer == 'Y') {
cout << "Enter a random number and we will tell you if it is greater than or less than " << const_num << ": " << endl;
cin >> random_num;
if (random_num > const_num) {
cout << random_num << " is greater than " << const_num;
}
else if (random_num == const_num) {
cout << random_num << " is the same as " << const_num << endl;
}
else {
cout << random_num << " is less than " << const_num << endl;
}
cout << "\nWant to try again? Type \"Y\" or \"N\"";
cin >> answer;
}
//=======================================================================================================================================
if (answer != 'Y' || answer != 'N') {
invalid_answer = 1;
}
//=======================================================================================================================================
while (invalid_answer == 1) {
cout << "I'm sorry what? Please note that answers are case sensitive. Answer again: ";
cin >> answer;
if (answer == 'Y') {
invalid_answer = 0;
}
else if (answer == 'N') {
cout << "Ok then, sorry to see you miss out" << endl;
keep_going = 1;
}
}
}
}
}
Whenever I say "N" for No I don't want to redo the random number checker, it doesn't change keep_going to 1 it just moves on to one of the other if or while statements below it. So when you input "N" it just outputs either "Enter a random number and we will tell you if it is greater than or less than " << const_num << ": " or "I'm sorry what? Please note that answers are case sensitive. Answer again: "
The problem is with this bit of code:
if (answer != 'Y' || answer != 'N') {
invalid_answer = 1;
}
When answer is 'N', answer != 'Y' is true and invalid_answer is set to 1 (because of short-circuit evaluation the rhs of the logical OR is not even evaluated - see quote below).
So the execution will enter the while
while (invalid_answer == 1)
and will print the statements.
You can correct this by:
if (answer == 'Y' || answer == 'N') { //if input is either 'Y' or 'N'
invalid_answer = 0;
}
else { //for all other inputs
invalid_answer = 1;
}
Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like regular function calls and always evaluate both operands
Also note that main should have the type int.
I figured it out right after I posted the question haha, basically the answer above was correct so I had to split that if statement into 2 others, in which I added an else statement to each also that said invalid_answer = 0; to make sure. But then after the user's second time using the program, if they wanted to quit it wouldn't let them and would just restart it again. I solved that by adding
if (answer == 'N') {
cout << "Ok then, sorry to see you miss out" << endl;
keep_going = 1;
}`
to the bottom of the while(answer == 'Y') loop.

Craps game problem, ignoring if statement

I'm currently in a class that wants me to make a craps game.
The problem is in int main on the second while statement comparing the point with the roll. It ignores the if statement and does the loop again, even though it hits the point or 7. Sometimes it works like it should and other times it repeats the loop a few times.
#include "pch.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int diceRoll() {
int x = 0, y = 0;
x = rand() % 6 + 1;
y = rand() % 6 + 1;
cout << "You rolled a " << x << " and a " << y << " which comes out to ------> " << x + y << " <-------" << endl;
return x + y;
}
bool playAgain() {
char ans;
cout << "Do you want to play again ?? Y to continue, N to quit." << endl;
cin >> ans;
while (ans != 'Y' || ans != 'y' || ans != 'n' || ans != 'N') {
if (ans == 'Y' || ans == 'y')
{
return true;
}
if (ans == 'N' || ans == 'n')
{
return false;
}
cout << "Do you want to play again ?? Y to continue, N to quit." << endl;
cin >> ans;
}
}
int main()
{
srand(time(NULL));
int dices, bid, point = 0;
int money = 50;
bool gameRunning = true;
bool didTheyWin;
while (gameRunning == true) {
if (money == 0) {
cout << "You have no money, ending game." << endl;
break;
}
cout << "Please enter a bid. You currently have $" << money << endl;
cout << "$";
cin >> bid;
while (bid > money) {
cout << "Please bet below your current balance: $" << money << endl;
cout << "$";
cin >> bid;
}
dices = diceRoll();
didTheyWin = false;
if ((dices == 7) || (dices == 11)) {
cout << "You won $" << bid << " !" << endl;
money = money + bid;
}
else if ((dices == 2) || (dices == 3) || (dices == 12)) {
cout << "You LOSE! You lost $" << bid << " !" << endl;
money = money - bid;
}
else {
point = dices;
cout << "The target number is > " << point << " <" << endl;
cout << "If you hit a 7 you lose, if you hit the target you win. \nYou automatically roll until one of these two things happen.\n";
while (didTheyWin == false) {
diceRoll();
dices = diceRoll();
if (dices == point) {
cout << "You won $" << bid << " !" << endl;
money = money + bid;
cout << "You now have $" << money << endl;
didTheyWin = true;
}
else if (dices == 7) {
cout << "You LOSE! You lost $" << bid << " !" << endl;
money = money - bid;
cout << "You now have $" << money << endl;
didTheyWin = true;
}
}
}
gameRunning = playAgain();
}
cout << "Thanks for playing. _END_" << endl;
return 0;
}
You call diceRoll twice, and ignore what you get back from the first call. You'll see the results of that first roll displayed, but they'll be ignored and you'll roll again.

I am doing the program the subtracting game (NIM) in one of my exercises its asking me for another loop around the main loop

// Exercise2.5.3.cpp : Defines the entry point for the console application.
// Revising of the program so that it keeps playing the game until the user wants to quit.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char ans;
char stop;
do
{
int total, n;
cout << "Welcome to NIM. Pick a starting total: ";
cin >> total;
while (total < 1){
cout << "Enter positive integer only. ";
cout << "Pick starting total: ";
cin >> total;
}
while (true) {
// Pick best reponse and print results.
if ((total % 3) == 2) {
total = total - 2;
cout << "I am subtracting 2. " << endl;
}
else {
total--;
cout << "I am subtracting 1." << endl;
}
cout << "New total is " << total << endl;
if (total == 0){
cout << "I win!" << endl;
break;
}
// Get user's response; must be 1 or 2.
cout << "Enter num to subtract (1 or 2): ";
cin >> n;
while (n < 1 || n > 2) {
cout << "Input must be 1 or 2." << endl;
cout << "Re-enter: " << endl;
cin >> n;
}
total = total - n;
cout << "New total is " << total << endl;
if (total == 0) {
cout << "You win!" << endl;
break;
}
}
cout << "Do you want to continue (Y/N)?\n";
cout << "You must type a 'Y' or an 'N'.\n";
cin >> ans;
} while ((ans != 'Y') && (ans != 'N') && (ans != 'y') && (ans != 'n') && (stop != "0"));
return 0;
}
It gives a error after I run / compile the code 1 IntelliSense: operand types are incompatible ("char" and "const char *")
Do I have to use a do while loop or a while loop around my main loop in order for the program to work correctly and executes exactly what is asking ?? so that the program keeps playing the game until the user wants to quit ??
This is the program I try with the do while loop but is not working correctly exactly how it wants to work.
You declare:
char stop;
then use a "0" here:
} while ((ans != 'Y') && (ans != 'N') && (ans != 'y') && (ans != 'n') && (stop != "0"));
Try '0' because:
"0" is a const char *
'0' is a const char
Or since you never use stop, just remove it:
} while ((ans != 'Y') && (ans != 'N') && (ans != 'y') && (ans != 'n'));

Converting Integers to Strings and If.. Else Boolean Functions C++

I am working on this assignment that requires me to create a game of rock, paper scissors for my programming class. I have ran into a couple issues that I am not fully educated about as I am still learning the basics of this language. My professor wants me to take in the users choice and the computers choice and then change it from an int to a string and print it out as "You chose: Rock" instead of "You chose: 1" which is what it is doing now. This part would be in the getComputerChoice() and getPlayerChoice() functions. Another issue I am having trouble with is my professor wants us to check if it was a tie or if the player won and I am trying to put these functions in an If else statement but I am not exactly sure what the proper way to declare the function in the else statement is. (This is commented out in the else part of the if statement in main all the way at the bottom)
My code is as follows:
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
using namespace std;
int getComputerChoice();
int getPlayerChoice();
bool isTie(int, int);
bool isPlayerWinner(int, int);
int getComputerChoice()
{
int comp;
string cpChoice;
comp = rand() % 3 + 1;
if (comp == 1)
{
cpChoice = "Rock";
}
else if (comp == 2)
{
cpChoice = "Paper";
}
else if (comp == 3)
{
cpChoice = "Scissors";
}
return comp;
}
int getPlayerChoice()
{
int userChoice;
string strChoice;
cout << "Rock, Paper, or Scissors?\n";
cout << "1) Rock\n";
cout << "2) Paper\n";
cout << "3) Scissors\n";
cout << "Please enter your choice : \n";
cin >> userChoice;
cout << '\n';
while(userChoice < 1 || userChoice > 3)
{
cout << "Invalid Selection\n";
cout << "Re-enter a number between 1 and 3\n";
cin >> userChoice;
}
if (userChoice == 1)
{
strChoice = "Rock";
}
else if (userChoice == 2)
{
strChoice = "Paper";
}
else if (userChoice == 3)
{
strChoice = "Scissors";
}
return userChoice;
}
bool isTie(string userChoice, string comp)
{
if (userChoice != comp)
return false;
else
return true;
}
bool isPlayerWinner(int userChoice, int comp)
{
if ((comp == 1 && userChoice == 2) || (comp == 3 && userChoice == 1) || (comp == 2 && userChoice == 3))
return true;
else
return false;
}
int main()
{
char selection;
int computerChoice;
int userChoice1;
string Rock;
string Paper;
string Scissors;
srand ((unsigned int)time(NULL));
do
{
cout << '\n';
cout << "ROCK PAPER SCISSORS MENU\n";
cout << "-------------------------\n";
cout << "p) Play Game\n";
cout << "q) Quit\n";
cout << "Please enter your choice : \n";
cin >> selection;
cout << '\n';
cout << '\n';
// cin >> selection;
if (selection == 'p' || selection == 'P')
{
computerChoice = getComputerChoice();
//string computerChoice = to_string(comp);
userChoice1 = getPlayerChoice();
//string userChoice1 = to_string(userChoice);
cout << "You chose: " << userChoice1 << '\n';
cout << "The computer chose: " << computerChoice << '\n';
if (isTie(computerChoice, userChoice1)== true)
{
cout << "You choose: " << userChoice1;
cout << "The computer chose: " << computerChoice;
cout << "It's a TIE!";
}
else //(isPlayerWinner(computerChoice, userChoice1));
{
cout << "You choose: " << userChoice1;
cout << "The computer chose: " << computerChoice;
cout << "You WIN!";
}
}
//else if (selection != 'p' || selection != 'q')
//{
// cout << "Invalid Selection. Try Again.\n";
// cout << '\n';
// cin >> selection;
//}
else if (selection == 'q' || selection == 'Q')
{
cout << "You have chosen to quit the program. Thank you for using the program!\n";
}
else if (selection != 'p' || selection != 'q')
{
cout << "Invalid Selection. Try Again.\n";
cout << '\n';
}
}while (selection != 'q');
}
ANOTHER NOTE: my professor doesn't want any void functions and doesn't want any global variables.
She told me that my isTie function was fine but didn't mention anything about the isPlayerWinner function. I believe it is fine and has no issues, I am just not sure how to declare it in the main if else statement. Any help would be appreciated and if you guys have any questions or need more info please let me know. Thanks in advance.
You pretty much have everything right.
Your getPlayerChoice() and getComputerChoice() functions right now are both returning an int that stand for the players choice. You calculate the name for that choice in those functions, but dont do anything with the actual string representing the choice. You either need to return the choice string, or make a function that takes in an int and returns name associated with that choice:
string getChoiceName(int choice)
{
string strChoice;
if (choice== 1)
{
strChoice = "Rock";
}
else if (choice== 2)
{
strChoice = "Paper";
}
else if (choice== 3)
{
strChoice = "Scissors";
}
return strChoice;
}
I prefer the method, as it make it easier to calculate the result of the match if you have the ints. There are a lot of other routes you could take, like making an enum representing choices - even the function I gave you here isn't great, but it should get you to a working state.

C++ Calculator Skipping Else Statement

I was making a simple calculator in C++. However the program does not completely function the way it should. When run, the trig if statement executes fine, however, the basic arithmetic else statement doesn't work. I have determined that the code is not executing the else statement and was wondering how to fix it. The code inside the else statement works fine, as I have commented out the if statement. Help?
Here is my code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
int main()
{
double input = 0;
double firstnumber = 0;
double secondnumber = 0;
std::string function;
std::string operation;
std::cout << "Enter your calculation: ";
std::cin >> function;
if(function == "sin" || "cos" || "tan")
{
if(function == "sin")
{
std::cin >> input;
std::cout << "The sine is " << sin(input) << std::endl;
system("PAUSE");
}
else if(function == "cos")
{
std::cin >> input;
std::cout << "The cosine is " << cos(input) << std::endl;
system("PAUSE");
}
else if(function == "tan")
{
std::cin >> input;
std::cout << "The tangent is " << tan(input) << std::endl;
system("PAUSE");
}
}
else
{
firstnumber = ::atof(function.c_str());
std::cin >> operation;
std::cin >> secondnumber;
double valueadd = firstnumber + secondnumber;
double valuesubtract = firstnumber - secondnumber;
double valuemultiply = firstnumber * secondnumber;
double valuedivide = firstnumber / secondnumber;
if(operation == "+")
{
std::cout << " = " << valueadd << std::endl;
system("PAUSE");
}
else if(operation == "-")
{
std::cout << " = " << valuesubtract << std::endl;
system("PAUSE");
}
else if(function == "*")
{
std::cout << " = " << valuemultiply << std::endl;
system("PAUSE");
}
else if(function == "/")
{
std::cout << " = " << valuedivide << std::endl;
system("PAUSE");
}
else
{
std::cout << "Error" << std::endl;
return 0;
}
}
return 0;
}
This line is wrong.
if(function == "sin" || "cos" || "tan")
It should be
if((function == "sin") || (function == "cos") || (function == "tan"))
Note that the check is actually meaningless because you already check for them each individually. You could tidy this up by doing this in a if, else if, else chain.
You must write out each condition separately. The following line of code compiles but it doesn't do what you think:
if (function == "sin" || "cos" || "tan")
Change it to the following:
if (function == "sin" || function == "cos" || function == "tan")
Since you want to do something different for each trig function, you should just have a single if...else if...else if...else if...else chain. There is no need to nest the if statements as you have. In fact, it is probably less efficient because you check each condition twice.
Change:
if(function == "sin" || "cos" || "tan")
into:
if ((function == "sin") || (function == "cos") || (function == "tan"))
What you have first calculates the expression "sin" || "cos" || "tan" and then tries to compare the string with that.
But, in fact, it's not really necessary to have this two-step process. You can simply do something like this:
if (function == "sin") {
std::cin >> input;
std::cout << "The sine is " << sin (input) << std::endl;
system ("PAUSE");
} else if (function == "cos") {
std::cin >> input;
std::cout << "The cosine is " << cos (input) << std::endl;
system ("PAUSE");
} else if (function == "tan") {
std::cin >> input;
std::cout << "The tangent is " << tan (input) << std::endl;
system ("PAUSE");
} else {
// It's neither sin, cos nor tan if you get here.
firstnumber = ::atof (function.c_str ());
// and the rest of your stuff in here.
}