0

I was recently trying out some code for an calculator, and i found one which worked..

But whatever i tried, this program would go off immediately after showing the answer on console. Please help me on this, i tried my best to actually make it stop. But it wouldnt work...

I'm using Visual Studio for the coding, If it is related to it, then inform me on it

#include <iostream>
#include <string>
#include <cctype>
#include<conio.h>

    int expression();

char token() {
    char ch;
    std::cin >> ch;
    return ch;
}

int factor() {
    int val = 0;
    char ch = token();
    if (ch == '(') {
        val = expression();
        ch = token();
        if (ch != ')') {
            std::string error = std::string("Expected ')', got: ") + ch;
            throw std::runtime_error(error.c_str());
        }
    }
    else if (isdigit(ch)) {
        std::cin.unget();
        std::cin >> val;
    }
    else throw std::runtime_error("Unexpected character");
    return val;

}

int term() {
    int ch;
    int val = factor();
    ch = token();
    if (ch == '*' || ch == '/') {
        int b = term();
        if (ch == '*')
            val *= b;
        else
            val /= b;
    }
    else std::cin.unget();
    return val;

}

int expression() {
    int val = term();
    char ch = token();
    if (ch == '-' || ch == '+') {
        int b = expression();
        if (ch == '+')
            val += b;
        else
            val -= b;
    }
    else std::cin.unget();

    return val;

}

int main(int argc, char **argv) {
    try {
        std::cout << expression();
    }
    catch (std::exception &e) {
        std::cout << e.what();

    }
    return 0;
}
Sneftel
  • 40,271
  • 12
  • 71
  • 104
  • 1
    See https://stackoverflow.com/questions/2529617/how-to-stop-c-console-application-from-exiting-immediately – Eyal D Jan 07 '18 at 09:37

1 Answers1

1

The best approach, in general, is to run your program from a command interpreter. I use cmd.exe. Most programmers nowadays, it seems to me, instead prefer Powershell, but I hate it (it's like COBOL to me). You can also use Cygwin, for a bash-shell-like experience. I don't recommend the beta bash shell in Windows 10 dev mode: it's unstable and might do Bad Things if you're not very very careful.

In Visual Studio just run the program via Ctrl+F5, which runs it without debugging.

To run with debugging from within VS, you can place a breakpoint on the last right curly brace of main.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331