简体   繁体   中英

C++ calculator doesn't work for * operator

I am learning c++ using Stroustrup's Programming Principles and Practice and there is this example code that one is to debug and make it work. I have made the corrections and when you enter an arithmetic expression that uses the + or - operator, it works. However when I enter an expression with the * operator, nothing happens. I have used debuggers to help me walk through the code but I've not been able to figure it out. The book uses a non standard include file std_lib_facilities.h

The actual calculator program is here . Can someone be kind enough to help me figure out why an expression like 2*3; produce no result while 2+3; works?

PS: as per the program a valid expression must have ; at the end to trigger a print. So 2+3; is correct and will trigger and print but 2+3 without a ; will just cause the cursor to just keep blinking. Please also not that, its the first attempt at producing a calculator program so it is missing a lot of features. My concern at the moment is to work out why a simple arithmetic expression involving the * operator does not work. Thanks.

[EDIT]

Thanks @KonradRudolph for your answer. One thing that stumped me though was, when I used the gdb debugger (I'm on linux), the debugger will not step into term when I enter an expression with a *. Now I know there was an error but, I was expecting it to at least step into the function and hang somewhere in there. Why won't the debugger step into a function that has an error? That will be more helpful.

Well you simply didn't make all necessary corrections.

In term :

    switch (t.kind) {
    case '*':
        left *= primary();
        t = ts.get();
    case '/':
        {    
            double d = primary();
            if (d == 0) error("divide by zero");
            left /= d; 
            t = ts.get();
            break;
        }
    default: 
        ts.putback(t);     // put t back into the token stream
        return left;
    }

case '*' is missing a break statement.

There may be more errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM