Calculator Problem (Console Skipping Lines)

Hi guys,

Here's the problem: I've made a simple calculator following instructions from learncpp.com. However, after putting in the operator, the program goes bananas.

This is what I was expecting:

Please enter a number: 1
Please enter an operator: +
Please enter another number: 2
Your result is: 3


However, after hitting Enter on entering the operator (in this example, +), this happened:

Please enter a number: 1
Please enter an operator: +
Please enter another number: Your result is: 0


Here's the code:

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
 #include <iostream>
#include <string>
using namespace std;

int GetUserInput1()
{
    cout << "Please enter a number: ";
    int userInput;
    cin >> userInput;
    return userInput;
}

int GetUserOperator()
{
    cout << "Please enter an operator: ";
    int theoperator;
    cin >> theoperator;
    return theoperator;
}

int GetUserInput2()
{
    cout << "Please enter another number: ";
    int userInputTwo;
    cin >> userInputTwo;
    return userInputTwo;
}

int CalculateResult(int FirstInput, int TheOperator, int SecondResult)
{
    if (TheOperator=='+')
        return FirstInput + SecondResult;
    if (TheOperator=='-')
        return FirstInput - SecondResult;
    if (TheOperator=='*')
        return FirstInput * SecondResult;
    if (TheOperator=='/')
        return FirstInput / SecondResult;
    
    return 0;
}

void PrintResult(int TheResult)
{
    cout << "Your result is: " << TheResult << endl;
}

int main()
{
    // First input
    int Input1 = GetUserInput1();
    
    // Operator
    int Operator = GetUserOperator();
    
    // Second Input
    int Input2 = GetUserInput2();
    
    // Go calculate or something
    int TheResult = CalculateResult(Input1, Operator, Input2);
    
    // Print the result
    PrintResult(TheResult);
    
    return 0;
}


So, anyone aware of what could be wrong?
Yes, you're casting a character that the user inputs into an int. There isn't really much wrong with it, but it's hard to exactly tell how iostream will handle the cast. I simply switched the operator function and variable to char and it worked fine.
Operator is a character, but you try to read it into an integer.
That read statement will fail, which sets the cin.fail() flag, and the rest of the input will also fail.

Change operator to type char.
Thanks, guys! I changed Operator and theoperator to a char and now it works fine :]
Topic archived. No new replies allowed.