1

I'm trying to make a basic calculator where the user can enter 2 numbers and an operator and the calculation will work. I can't figure out why I am getting this error and I am not entirely sure what this error means because I am new to c++ having only had experience with some java.

Here is what I have:

Calculation.h

#include <iostream>
using namespace std;

class Calculation{
private:
    int x;
    int y;

public:
    Calculation();
    int calculateAddition(int, int);
    int calculateSubtraction(int, int);
    int calculateMultiplication(int, int);
    int calculateDivision(int, int);
};

Calculation.cpp

#include "Calculation.h"

Calculation::Calculation(){
    x = 0;
    y = 0;
}

int Calculation::calculateAddition(int x, int y){
    return x + y;
}

int Calculation::calculateSubtraction(int x, int y){
    return x - y;
}

int Calculation::calculateMultiplication(int x, int y){
    return x * y;
}

int Calculation::calculateDivision(int x, int y){
    return x / y;
}

Main.cpp

#include <iostream>
#include <sstream>
#include <string>
#include "Calculation.h"
using namespace std;

int main(){
Calculation calc;
int i = 0;
char k;
int x;
int y;
char j = 'a';
string inputCalc;
stringstream str;

while(j != 'q'){
    cout << "1. Make Calculation" << endl;
    cout << "2. Quit" << endl;
    cin >> i;
    if(i == 1){
        cout << "Input calculation:" << endl;
        cin >> inputCalc;
        k = inputCalc.at(2);
        str << inputCalc.at(1);
        str >> x;
        str << inputCalc.at(3);
        str >> y;
        if (k == '+'){
            calc.calculateAddition(x, y);
        }
        else if (k == '-'){
            calc.calculateSubtraction(x, y);
        }
        else if (k == '*'){
            calc.calculateMultiplication(x, y);
        }
        else if (k == '/'){
            calc.calculateDivision(x, y);
        }
        else{
        }
    }
    else if(i == 2){
        j = 'q';
    }
    else{
        cout << "Invalid input. Please enter 1 or 2." << endl;
    }
}
}

EDIT: Ahhh thank you, I forgot that everything starts from 0. Silly me.

2 Answers 2

1

Assume the input in cin >> inputCalc to be '1+2'. input.at(0)=='1', input.at(1)=='+' and input.at(2)==2. input.at(3) is out of range.

Sign up to request clarification or add additional context in comments.

Comments

1

I think that the error occurs in some of the statements as this

str << inputCalc.at(3);

Are you sure that inputCalc has at least four characters that this statement will be valid? Take into account that valid range of indecies is [0, length() - 1]

std::out_of_range is a standard exception that is thrown by std::string member function at().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.