Hello everyone. Im new to C++ and have been learning for the past few weeks but ive been having a problem with a program I created.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main () {
float fNum1;
float fNum2;
char cResponse [20];
float fProduct;
float fSum;
cout << " Welcome To Evans Addition And Multiplication Calculator " << endl << endl;
cout << " What Would You like To Do? " << endl << endl;
cout << " 1 - Multiplication " << endl << endl;
cout << " 2 - Addition " << endl << endl;
cout << " ";
cin >> cResponse;
if (cResponse == "Multiplication"||"multiplication"||"1") {
cout << "\n\n You Have Chosen Multiplication." << endl << endl;
cout << " Please Enter Your First Number" << endl;
cin >> fNum1;
cout << " Please Enter Your Second Number" << endl;
cin >> fNum2;
fProduct = fNum1 * fNum2;
cout << " The Product Of " << fNum1 << " and " << fNum2 << " is " << fProduct << endl;
}else if (cResponse == "Addition"||"addition"||"2") {
cout << "\n\n You Have Chosen Addition." << endl << endl;
cout << " Please Enter Your First Number" << endl;
cin >> fNum1;
cout << " Please Enter Your Second Number" << endl;
cin >> fNum2;
fSum = fNum1 * fNum2;
cout << " The Sum Of " << fNum1 << " and " << fNum2 << " is " << fSum << endl;
} else {
cout << "\n\n Sorry But You Have Chosen An Invalid Choice" << endl;
}
return 0;
}
Its a simple calculator as you can see. Basically the problem is it always results in the if statement, and never goes to the else if and else. Anyone mind helping me out in why it wont work.
if (cResponse == "Multiplication"||"multiplication"||"1") {
The above piece of code does not do what you think it does. Any value other than 0, NULL and false is considered to be true:
If cResponse == "Multiplication" Or True Or True ...
In other words, whether or not cResponse == "Multiplication", the || operator makes the program execute that block of code anyway because it sees that at least one statement is true.
Instead, you should try this: if (cResponse == "Multiplication" || cResponse == "multiplication" || cResponse == "1") {
Don't forget to fix your else if statement as well.
However, you will run into problems comparing C strings that way. Try using C++ strings instead.
[code] Code tags (your code goes here) [/code]
Everything that is not 0 will be threat as true
1 2
//if (cResponse == "Multiplication"||"multiplication"||"1")
if (cResponse == "Multiplication"|| cResponse =="multiplication"|| cResponse =="1") // should be like this
However you can't compare cstrings in that way (use strcmp or use strings instead)