C++ Calculator Skipping Else Statement - c++

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.
}

Related

Validating user input isn't displaying my cout invalid message. Why?

I'm trying to write a Euro/USD converter. I'm brand new to programming and c++. I don't know what I did wrong. I don't have any errors, but whenever I don't type the string im checking for the
std::cout << "Invalid. Please type Euros or USD. No stupid weird CAPS." << std::endl;
doesn't display.
Here's the full code:
#include <iostream>
#include <limits>
int main() {
while (true) {
// Used later when validating user input.
full_restart:
// Initial convert selector:
std::cout << "What currency do you want to convert? Euros or USD?\nPlease type Euros or USD:" << std::endl;
std::string currency_type{"hello"};
restart:
std::cin >> currency_type;
// Validating user input:
while (true) {
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid. Please type Euros or USD. No stupid weird CAPS." << std::endl;
goto restart;
} else if (!std::cin.fail()) {
break;
}
}
if (currency_type == "euros" || currency_type == "Euros" || currency_type == "EUROS") {
std::cout << "How many Euros do you want to convert to USD?\nEnter the number: " << std::endl;
double euro_amount_to_convert{0};
euro_restart:
std::cin >> euro_amount_to_convert;
while (true) {
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid. Please enter either Integer or Decimal." << std::endl;
goto euro_restart;
} else if (!std::cin.fail()) {
break;
}
}
double euros_converted_to_usd = euro_amount_to_convert * 1.11237;
std::cout << euro_amount_to_convert << " euros equals " << euros_converted_to_usd << " USD." << std::endl;
std::cout << "Would you like to convert another currency?\nPlease type 'Y' or 'N'" << std::endl;
char go_again{'a'};
std::cin >> go_again;
euro_convert_again:
std::cout << "Would you still like to convert another currency?\nPlease type 'Y' or 'N'" << std::endl;
std::cin >> go_again;
while (true) {
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input." << std::endl;
goto euro_convert_again;
} else if (!std::cin.fail()) {
break;
}
}
if (go_again == 'Y' || go_again == 'y') {
goto full_restart;
} else if (go_again == 'N' || go_again == 'n') {
break;
}
}
if (currency_type == "usd" || currency_type == "Usd" || currency_type == "USD") {
std::cout << "How many USD do you want to convert to Euros?\nEnter the number: " << std::endl;
double usd_amount_to_convert{0};
usd_restart:
std::cin >> usd_amount_to_convert;
while (true) {
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid. Please enter either Integer or Decimal." << std::endl;
goto usd_restart;
} else if (!std::cin.fail()) {
break;
}
}
double usd_converted_to_euros = usd_amount_to_convert * 1.11237;
std::cout << usd_amount_to_convert << " USD equals " << usd_converted_to_euros << " Euros." << std::endl;
std::cout << "Would you like to convert another currency?\nPlease type 'Y' or 'N'" << std::endl;
char go_again{'a'};
std::cin >> go_again;
usd_convert_again:
std::cout << "Do you still want to convert another currency?\nPlease type 'Y' or 'N'" << std::endl;
std::cin >> go_again;
while (true) {
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input." << std::endl;
goto usd_convert_again;
} else if (!std::cin.fail()) {
break;
}
}
if (go_again == 'Y' || go_again == 'y') {
goto full_restart;
} else if (go_again == 'N' || go_again == 'n') {
break;
}
}
}
std::cout << std::endl;
return 0;
}
Also, I'm aware there are probably many better ways to do this, this is just practice for me. I'm pretty sure it's the loops since this is the first time I've used them.
cin.fail() doesn't become true just because the input isn't what you want it to be. The compiler can't read your mind. If you want to restrict the input to certain strings you have to check for that explicitly.
E.g.
std::string currency_type{"hello"};
std::cin >> currency_type;
if (currency_type == "euros" || currency_type == "Euros" || currency_type == "EUROS") {
...
} else if (currency_type == "usd" || currency_type == "Usd" || currency_type == "USD") {
...
} else {
std::cout << "Invalid. Please type Euros or USD. No stupid weird CAPS." << std::endl;
}
cin.fail() does become true if a read fails completely, e.g. if you try to read an integer, but the user types in letters. But that's a different situation to this.
You only show that message when std::cin.fail(), but there's no reason for this to be true.
You read into a string, which is always going to work. The computer does not know that you only wanted the string "Euros" or the string "USD" to be valid.
You'll want to replace your check with a value comparison.
currency_type is a std::string. This means that cin will never enter a failed state as whatever you enter can be placed in a string. What you need to do is inspect what is in the string, and if it is not what you want then give an error message. That would mean you need a check like:
if (!(currency_type == "euros" || currency_type == "Euros" || currency_type == "EUROS"
currency_type == "usd" || currency_type == "Usd" || currency_type == "USD"))
{
std::cout << "Invalid. Please type Euros or USD. No stupid weird CAPS." << std::endl;
goto restart;
}

How to use character value in if condition (c++)

{
cout << "type 3 to add ,type 1 to multiply,type division to divide,type 2 to subtract" << endl;
cin >> function;
if (function == 1)
{
multiply();
}
else if (function == 2)
{
subtract();
}
else if (function == 3)
{
add();
}
else if (function == 4)
{
division();
}
cout << "press x to quit or anything else to restart " << endl;
cin >> input;
} while (input !='x');
system("pause");
return 0;
}
in this code i am unable to have a character value with if
eg-if (function=='add') it does not work
if I use if(function='add') everything inside is skipped to the last cout which says
press x to quit or anything else to restart
'add' is a multicharacter literal and is an int type (note the single quotation characters). You almost certainly don't want to do that as then you're in the murky waters of implementation-defined behaviour.
If you want to be able to read in strings then why not use a std::string as the type for function, and use if (function == "add") &c. ? You can even retain your notation cin >> function!
As suggested by Bathsheba, you could implement this functionality with std::string. Bellow you have an example of how you could do this.
#include <iostream>
#include <string>
void multiply() {
std::cout << "multiplication called" << std::endl;
}
void add() {
std::cout << "add called" << std::endl;
}
void subtract() {
std::cout << "substract called" << std::endl;
}
void division() {
std::cout << "division called" << std::endl;
}
int main()
{
using namespace std;
string input;
do {
cout << "type add, multiply, division, or subtract" << endl;
cin >> input;
if (input == "multiply") {
multiply();
}
else if (input == "substract") {
subtract();
}
else if (input == "add") {
add();
}
else if (input == "division") {
division();
}
else {
cout << "You inputed: " << input << endl;
cout << "Command not recognized, please try again" << endl;
continue;
}
cout << "press x to quit or anything else to restart ";
cin >> input;
} while (input != "x");
return 0;
}

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.

Inclusion of trigonometry functions in simple calculator, C++

I am currently working on a small and simple calculator program and it's coming along very well, but I'm just trying to make some improvements. It includes adding in functions for sin/cos/tan and abs.
I couldn't think of any other way which I could include them in as I have already declared my variables as float earlier on in the code.
#include <iostream>
int main() {
//Variables that user inputs.
float a, b;
char op;
//Input them in the order
std::cin >> a >> op >> b;
//Addition
if (op == '+') {
std::cout << a << '+' << b << '=' << a+b;
}
//Subtraction
else if (op == '-') {
std::cout << a << '-' << b << '=' << a-b;
}
//Multiplication
else if (op == '*') {
std::cout << a << '*' << b << '=' << a*b;
}
//Division
else if (op == '/') {
std::cout << a << '/' << b << '=' << a/b;
}
return 0;
}
Any help is greatly appreciated!
EDIT: Apologies. Realised I didn't include the question. How do I include the trigonometric functions?
You really don't want to do this , but for your curiosity, can have something like following :
(make sure you do necessary checks)
/* Sine */
else if (op == 's') {
std::cout << a<<"*sin(" << b << ")=" << a*sin(b);
}
/* Cosine */
else if (op == 'c') {
std::cout << a<<"*cos(" << b << ")=" << a*cos(b);
}
/* Tangent */
else if (op == 't') {
std::cout << a<<"*tan(" << b << ")=" << a*tan(b);
}
/* Absolute */
else if (op == 'a') {
std::cout << a<<"*abs(" << b << ")=" << a*fabs(b);
}

C++ Troubleshooting my command line calculator

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);
}