1

I was coding an equation funciton in c++. My question if fairly straight forward. I'm reading through a file "4 + 5". So I store it into a string.

My question:

how do I output 9? because if I just cout << myString ...the output is just "4+5"

user3121369
  • 417
  • 2
  • 6
  • 13
  • If you're looking for a quick way to do it, I don't think there is one. You pretty much have to write it yourself from scratch, and it's university-level stuff. – user253751 Feb 12 '16 at 01:26
  • @immibis Well, depends on what you need. A recursive descent parser for `+,*,()` without fancy error handling is pretty straight forward. Fred Overflow did a video on that btw. But as it stands, the question is certainly too broad. – Baum mit Augen Feb 12 '16 at 01:29
  • 1
    Does your equation always sum of two numbers? – d40a Feb 12 '16 at 01:30

3 Answers3

0

You'll probably need to do a bit more work than it seems your expecting. You'll need to read in each operand and operator separately into string variables. Next, convert number strings to integers once you've confirmed they are indeed integers. You'll probably have a character which has the operand in it and you'll do something like a switch case to determine what the actual operand is. From there you'll need to do the operation determined in the switch case on the values stored in your variables and output the final value.

Brian Riley
  • 926
  • 1
  • 7
  • 12
0

http://ideone.com/A0RMdu

#include <iostream>
#include <sstream>
#include <string>

int main(int argc, char* argv[])
{
    std::string s = "4 + 5";
    std::istringstream iss;
    iss.str(s); // fill iss with our string

    int a, b;
    iss >> a; // get the first number
    iss.ignore(10,'+'); // ignore up to 10 chars OR till we get a +
    iss >> b; // get next number 

    // Instead of the quick fix I did with the ignore
    // you could >> char, and compare them till you get a +, - , *, etc. 
    // then you would stop and get the next number.

    // if (!(iss >> b)) // you should always check if an error ocurred.
            // error... string couldn't be converted to int...

    std::cout << a << std::endl;
    std::cout << b << std::endl;
    std::cout << a + b << std::endl;

    return 0;
}
Jts
  • 3,447
  • 1
  • 11
  • 14
0

Your output is "4+5" because "4+5" is like any other string for ex: "abc", and not 4 and 5 being integers and + being an operator . If it involves more than just adding 2 numbers you can convert your infix expression to a postfix expressing and evaluate using a stack.