-1

enter image description hereI wrote C++ program which asks the user for two numbers and operator and gives the output based on the input.I think everything is correct but the output is not the desired output.

#include <iostream>

using namespace std;

int main()
{
    int num1;
    string op;
    int num2;
    string result;

    cout << "Enter a number: ";
    cin >> num1;
    cout << "Enter a operator: ";
    cin >> op;
    cout << "Enter another number: ";
    cin >> num2;

    if (op == "+"){  //if user types '+' the result is num1 + num2
        result = num1 + num2;
        //cout << result;
    }else if (op == "-"){ //if user types '-' the result is num1 - num2
        result = num1 - num2;
       // cout << result;
    }else if (op == "*"){ //if user types '*' the result is num1 * num2
        result = num1 * num2;
        //cout << result;
    }else if (op == "/"){ //if user types '/' the result is num1 / num2
        result = num1 / num2;
        //cout << result;
    }else{
        cout << "Invalid operator...";
    }
    cout << result;



    return 0;
}

The output should be integer.But the output is just a diamond.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Read [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and compile (using [GCC](http://gcc.gnu.org)...) with `g++ -Wall -g` – Basile Starynkevitch Oct 16 '19 at 16:33

2 Answers2

4

Declare the variable result as having the type int

int result = 0;

Or maybe it is even better to declare it as

long long int result = 0;

and use it like

result = static_cast<long long int>( num1 ) * num2;

In your program it has the type std::string

string result;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Of course, since the OP is using division, it may be useful to use a `double` or `float` instead to store the result. But that would obviously be up to the OP. –  Oct 16 '19 at 17:21
0

You are assigning a integer value to a string so I think so it is converting that integer value to character value and giving that emojis. My case was same as your, I was assigning integer value to a string. But I then declared that integer value as a character value and it worked fine then.

Also the best approach is to use to_string() function to change the integer value to a character value.