Hello, this is kinda my first program. I would like to know how to clean the screen so only this code would stay in the console

cout<<"Welcome to calculator!\n\n";
    cout<<"[*] - a * b\n[/] - a / b\n[-] - a - b\n[+] - a + b\n\n";

I m also having trouble that when i make wrong ccalculation suchs as 5+5+, the program is looping the 5 + 5 calculation and ignores any input.

#include <iostream>

using namespace std;

int main ()
{
    double a;
    double b;
    char oper;
    int exit = 0;

    cout<<"Welcome to calculator!\n\n";
    cout<<"[*] - a * b\n[/] - a / b\n[-] - a - b\n[+] - a + b\n\n";

    do {

    cout<<"Calculator is now ready to calculate\n\n";

    cin>>a >>oper >>b;
    cout<<endl;

    if (oper == '+')
        {
            cout<<a<<" + "<<b<<" = "<<a+b<<endl<<endl;
            cout<<"Press 1 to exit or 0 to continue: ";
            cin>>exit;
            cout<<endl;
        }

    else if (oper == '-')
        {
            cout<<a-b;
        }

    else if (oper == '*')
        {
            cout<<a*b;
        }

    else if (oper == '/')
        {
            cout<<a/b;
        }

    else
        {
            cerr<<"Not a valid operation. Try again\n\n";
        }

    }while (exit < 1);

    cout<<"Thank you for using...Press any key.... \n";

    return 0;
}

Dani AI

Generated

Good first project, . The looping you see after typing something like 5+5+ is classic stream state behavior that pointed out: the last '+' is left in the buffer and the next formatted read fails immediately. Two fixes help: 1) always validate the read before you compute, and 2) on failure, clear the error flags and discard the rest of the line so you start clean on the next prompt. Also, only whitespace separates tokens; operators like '+', '-', '*', '/' are not whitespace. So 5 + 5 can be read as three tokens, but 5+5+ leaves that trailing '+' behind and poisons the next read.

A simple, robust pattern is to read a whole line and parse it yourself. That way you either consume the entire input or reject it and try again.

#include <string>
#include <sstream>
#include <limits>

bool read_expr(double& a, char& op, double& b) {
    std::string line;
    if (!std::getline(std::cin, line)) return false;            // EOF or error
    std::istringstream ss(line);
    if (!(ss >> a >> op >> b)) return false;                    // missing pieces
    char extra;
    if (ss >> extra) return false;                              // trailing junk like the last '+'
    return op=='+' || op=='-' || op=='*' || op=='/';            // only allow valid ops
}

In your loop, call read_expr, check division by zero, then use your switch to compute. If read_expr returns false, print a friendly error and prompt again. This avoids the sticky-fail problem without sprinkling cin.clear()/ignore() everywhere. And as suggested, ask whether to exit once at the bottom of the loop; no need to repeat that in each case.

About clearing the screen: there is no standard C++ way. If you really want it and can live with terminals that support ANSI, you can redraw with this escape sequence:

std::cout << "\x1b[2J\x1b[H";  // clear screen and move cursor to top-left

Otherwise, keep it simple: just print a fresh prompt and results each iteration, as and lean toward.

Recommended Answers

All 6 Replies

To clear your screen you can use system("CLS") - keep in mind this makes your program less portable though.

The reason you continuously loop when you enter bad input is because you're trying to accept a number, but are receiving a char, and your input buffer is overflowing.

Try flushing the input stream after you get the data you want.

Also, I would recommend using a switch rather than multiple IFs.

commented: He didn't say he was on a Windows system. -4
commented: no reason to downvote, you can just say that in the command below him WaltP! +5

The reason you continuously loop when you enter bad input is because you're trying to accept a number, but are receiving a char, and your input buffer is overflowing.

It's not because of an input buffer overflow. When you try to read a non-digit into an integer, the read fails. The input buffer remains the same. Next time you try to read, since that character is still there, the input fails again. And again. And ... you get the idea.

1) Test your read to see if it was successful. Don't ask How? Look it up. It's part of cin error checking.
2) If it fails, clear the input buffer as Duki's link suggests. Be sure to process the error in your code. Don't just go on your merry way and execute the code as if nothing happened.

Also, I would recommend using a switch rather than multiple IFs.

So would I, but only if you've learned them.

commented: Thanks for the correction. :) +10

I have learned the switch but how could i use it in this case? My variable "oper" gets the operator from user input and uses it to detect what operation to do. But if i m correct then the switch need numerical variable.

And isnt there any other way to clear screen other than involving system in it. Cause i would like my program to be as independent as possible.

Thanks for all answers

EDIT: Nvm about the switch, i was wrong obviously. Did some researching and found useful info :)

My code looks like this now

#include <iostream>

using namespace std;

int main ()
{
    double a;
    double b;
    char oper;
    int exit = 0;

    cout<<"Welcome to calculator!\n\n";
    cout<<"[*] - a * b\n[/] - a / b\n[-] - a - b\n[+] - a + b\n\n";

    do{
    cout<<"Calculator is now ready to calculate\n\n";
    cin>>a >> oper >> b;

        switch (oper)
            {
                case '+':
                cout<<a<<" + "<<b<<" = "<<(a+b)<<endl;
                cout<<"Press 1 to exit\n";
                cin>>exit;
                break;

                case '-':
                cout<<a<<" - "<<b<<" = "<<(a-b)<<endl;
                cout<<"Press 1 to exit\n";
                cin>>exit;
                break;

                case '/':
                cout<<a<<" / "<<b<<" = "<<(a/b)<<endl;
                cout<<"Press 1 to exit\n";
                cin>>exit;
                break;

                case '*':
                cout<<a<<" * "<<b<<" = "<<(a*b)<<endl;
                cout<<"Press 1 to exit\n";
                cin>>exit;
                break;
            }
        }while(exit != 1);


    cout<<"Thank you for using...Press any key.... \n";

    return 0;


}

Should i make function for exiting rather than typing it in all the time (Hardcoding is the expression i think ?) And i m still working on the loop problem.

And isnt there any other way to clear screen other than involving system in it. Cause i would like my program to be as independent as possible.

Output '\n' 25 to 50 times. Depending on how many lines in your console.

Should i make function for exiting rather than typing it in all the time (Hardcoding is the expression i think ?)

No. Just remove the lines

cout<<"Press 1 to exit\n";
    cin>>exit;

from your switch and put them once at the bottom of the loop.

Do '+' signs work as SPACES in user input. For instance when i have code

cout<<"Enter two numbers ";
cin>>a >>b

and then when i run it and am asked to enter two numbers then SPACE between words works like enter.

Input to console: Hello World

Then the HEllo would be assigned to variable a and World to variable b. So the question is do operators like +,-,/,* have the same effect ?

>>So the question is do operators like +,-,/,* have the same effect ?

No.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.