Help with a basic calculator (brand new to programming)

I have been following some tutorials on learncpp.com and am trying to program a calculator but have hit a snag. It always outputs the second number, it never gives the final product. Please don't think im dumb, i just started, haha. Please help me /:

Main file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include "head.h"

using namespace std;

int main()
{
    int numberone;
    int numbertwo;
    int answer;
    std::string mathop;
    numberone = Readnumber();
    mathop = Getoperator();
    numbertwo = Readnumber();
    answer = calcy(numberone, numbertwo, mathop);
    Answerwriter(answer);
    return 0;
}

Functions file
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <string>

using namespace std;


int Readnumber()
{
    cout << "Please input a number" << endl;
    int x;
    cin >> x;
    return x;
}

int Getoperator()
{
    string oper;
    cout << "Please input your operation" << endl;
    cin >> oper;
}

int calcy(int x, int y, std::string oper)
{
    int answer;
    if(oper == "+")
    {
        answer = x + y;
    }
    if(oper == "-")
    {
        answer = x - y;
    }
    if(oper == "/")
    {
        answer = x / y;
    }
    if(oper == "*")
    {
        answer = x * y;
    }
    return answer;

}

void Answerwriter(int ans)
{
    cout << ans;

}

Header file
1
2
3
4
5
6
7
8
9
10
11
#ifndef HEAD_H_INCLUDED
#define HEAD_H_INCLUDED
#include <string>

int Readnumber();
int Getoperator();
int calcy(int x, int y, std::string oper);
void Answerwriter(int ans);

#endif
In your GetOperator() function, you aren't returning anything. When it gets to your calcy() function, It doesn't have an operator, so it just returns answer, which has no value set.

Your GetOperator() function should look something like this:

1
2
3
4
5
6
7
std::string Getoperator()
{
    string oper;
    cout << "Please input your operation:";
    cin >> oper;
    return oper;
}


Edit:
You can also change your "calcy()" function like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int calcy(int x, int y, std::string oper)
{
    if(oper == "+")
        return (x+y);
    if(oper == "-")
        return (x-y);
    if(oper == "*")
        return (x*y);
    if(oper == "/")
        return (x/y);

    std::cout << "Invalid operator entered...." << std::endl;
    return 0;
}
Last edited on
Topic archived. No new replies allowed.