0

I'm programming a calculator and when I choose for example first option, program stops. I can't enter any numbers. What do I have to change in my code to make the methods work? I don't know what I have to do.

main.cpp:

#include "stdafx.h"
#include <iostream>
#include "Calculator.h"

using namespace std;

float Calculator::add()
{
    cout << "Enter 1 number: ";
    cin >> a;
    cout << "Enter 2 number: ";
    cin >> b;
    system("cls");

    cout << a + b << endl;

    return 0;
}

float Calculator::sub()
{
    cout << "Enter 1 number: ";
    cin >> a;
    cout << "Enter 2 number: ";
    cin >> b;
    system("cls");

    cout << a - b << endl;

    return 0;
}

float Calculator::mul()
{
    cout << "Enter 1 number: ";
    cin >> a;
    cout << "Enter 2 number: ";
    cin >> b;
    system("cls");

    cout << a*b << endl;

    return 0;
}

float Calculator::div()
{
    cout << "Enter 1 number: ";
    cin >> a;
    cout << "Enter 2 number: ";
    cin >> b;
    system("cls");

    cout << a / b << endl;

    return 0;
}

int main()
{
    int choose;

    Calculator k1;

    cout << "1.Add\n";
    cout << "2.Sub\n";
    cout << "3.Mul\n";
    cout << "4.Div\n";
    cout << "Choose: ";
    cin >> choose;

    if (choose == '1')
        k1.add();
    else if (choose == '2')
        k1.sub();
    else if (choose == '3')
        k1.mul();
    else if (choose == '4')
        k1.div();


    system("pause");
    return 0;
}

Calculator.h:

#pragma once
#ifndef Calculator_h
#define Calculator_h

class Calculator {
private:
    float a, b;
public:
    float add();
    float sub();
    float mul();
    float div();
};

#endif
abs
  • 31
  • 1
  • 2

1 Answers1

5

You are reading choose as an int: int choose; so you have to treat it as one:

if (choose == 1)
    k1.add();
else if (choose == 2)
    k1.sub();
else if (choose == 3)
    k1.mul();
else if (choose == 4)
    k1.div();

Explanation as requested:

if (choose == '1')

This is not wrong syntactically speaking because simply C++ is casting implicitly the char '1' to its ASCII code which is an int of value 49.

You were literally doing the following: if (choose == 49) instead of if (choose == 1)

Oussama Ben Ghorbel
  • 2,132
  • 4
  • 17
  • 34