Trying to make my first 4-way calculator..

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace 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.
1
2
3
4
5
6
7
8
9
10
char user_input;
if(user_input == 'A')
{
   //code 
}
if(user_input == 'S')
{
  /code
}
etc...
Last edited on
Thank you for your quick and helpful reply.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

using namespace std;

int main()
{
int n1;
int n2;
char user_input;
cout << "I need a function, please type multiplication(M), division(D), addition(A), or subtraction(S)\n";
if(user_input == 'A')
    {
    cout << "Ok you choose addition, please provide 2 numbers to finish the syntax";
    cin >> n1;
    cin >> n2;
    cout << n1+n2;
}
if(user_input == 'S')
{
    cout << "Ok you choose subtraction, please provide 2 numbers to finish the syntax";
    cin >> n1;
    cin >> n2;
    cout << n1-n2;
}
return 0;
}
ehh you actually have to get the input from the user ;p.

I thought you'd put that in yourself
cin>>user_input;
Last edited on
Thank you. I am still very new to this, got 1 hour of experience :P.
Topic archived. No new replies allowed.