Home > Enterprise >  My program doesn't work when I enter it in the terminal
My program doesn't work when I enter it in the terminal

Time:02-02

I'm trying to write a calculator program using standard input redirection, but for some reason my code doesn't load anything when I try it. The calculator program should compute expressions involving addition, subtraction, and the notation X^ which stands for X^2.

In my text file, I have the formulas

5^;
1000   6^ - 5^   1;

and my code is

int main()
{
    int answer, num;
    char sign;
    cin >> answer;

    while (cin >> sign)
    {
        if (sign == '^')
        {
            answer = answer * answer;
        }
        else if (sign == ' ')
            {
                cin >> num;
                cin >> sign;
                if (sign == '^')
                {
                    answer  = num * num;
                }
                else
                {
                    answer  = num;
                }
            }
             else if (sign == '-')
             {
                cin >> num;
                cin >> sign;
                if (sign == '^')
                {
                    answer -= num * num;
                }
                else
                {
                    answer -= num;
                }
             }
                else 
                {
                    cout << answer << endl;
                    cin >> answer;
                }
    }

    return 0;
}

CodePudding user response:

You always read a string. Better embrace that. From that point on, you need to parse the expression. So, if your language only allows 1 line expressions, read the whole line:

std::string line;
getline(std::cin, line);

Then parse the string and evaluate it.

CodePudding user response:

(I'm not sure what you are getting at as not enough information was given, but this is my attempt on trying to answer your question as accurately as possible):

When you declare any variable you must put the data type first:

int next;

or

char next = 'a'; //or whatever letter you want to declare here

char only works for singular letters based on the ASCII values (ASCII).

It would greatly help if you post some code to provide more context to your problem, so that way users know what your specific problem is in order for us to provide you with the best suggestions/solutions possible!

  •  Tags:  
  • Related