I have recently started learning C++, I do not have much experience with it but I believe I have the basics down.
The code below is supposed to output a specific line depending on what letter I type, when I type A an addition line should pop up, when I type S subtraction should come up. However, when I type S the addition line pops up. Why is this happening? I think the problem is located at where I am testing for the letters themselves.
#include <iostream>
usingnamespace std;
int main()
{
char M;
char D;
char A;
char S;
int n1;
int n2;
cout << "I need a function, please type multiplication(M), division(D), addition(A), or subtraction(S)\n";
if(cin >> A ){
cout << "Ok you choose addition, please provide 2 numbers to finish the syntax";
cin >> n1;
cin >> n2;
cout << n1+n2;
}
if(cin >> S ){
cout << "Ok you choose subtraction, please provide 2 numbers to finish the syntax";
cin >> n1;
cin >> n2;
cout << n1-n2;
}
return 0;
}
char A;(etc) just declares a variable called A of type char. Some random character will be stored in it. So cin >> A will (unless the null character happens to be stored in it) always evaluate to true. Hence the first if statement will be executed irrespective of what letter you enter
You need to do this char addition = 'A' to actually store the character A in the variable. Also you don't really need 4 variables for this just 1 variable for user input would do
like so.
I have tried using the user_input char, but when I do this the console skips the part where I have to type something in and just returns the execution time. (I am using codeblocks).