extracting numbers and characters from a string, which doesn't follow a specific format? (postfix calculator)

StackOverflow https://stackoverflow.com/questions/2392178

Question

I'm having trouble separating numbers and characters from my input string. The purpose of my program is to add,subtract,multiply and divide in postfix so i cant predict the input form as it can be anything from 2 2 3 + * (answer being 10) to 2 2 + 3 * (answer being 12). So i cant use sscanf to extract the numbers and the operator character without having a specific format to the input string. What should i do here?

Was it helpful?

Solution

Well, to process postfix you're going to want to implement a stack, so you should push each number onto a stack as you get it, each operator pops two off the stack and pushes the result back.

OTHER TIPS

One way is to use scanf("%s") which will return characters up to the next whitespace. Or you could use getc to get characters one at a time.

edit:

I see from comments that you are using gets to read in a whole line, in that case, you might be better off using strtok in a loop to break the line up into tokens and then look at the first character of each token to decide what to do with it.

char line[MAX_LINE];
// read in the line 

char * pTok = strtok(line, " \t");
while (pTok)
{
    char ch = pTok[0];
    if (isdigit(ch))
       //handle number

    if (ch == '+')
       //handle addition operator

    ...
    pTok = strtok(NULL, " \t");
}

I'd probably do this by grabbing a whole line, then have a function taking a string, an offset and a return struct. The return struct contains the start and end offset of the token, the token type (operator, argument) and possibly some other things.

Alternatively, split it into two functions, one that checks for a number and one that checks for an operator.

I would recommend using Boost.Spirit Qi, which is a really nice parser library. The first example is a calculator...

http://www.boost.org/doc/libs/1_42_0/libs/spirit/doc/html/spirit/introduction.html

A standard-library only solution:

// Get a line of user input (simplifies I/O)
std::string line;
if (!std::getline(std::cin, line)) throw std::runtime_error("Unable to read line");
// Process the line as an input string stream
std::istringstream iss(line);
while (true) {
    unsigned int val;
    if (iss >> val) {
        // TODO: Handle a numeric value (in val)
        continue;
    }
    iss.clear(); // Clear the error state
    char ch;
    if (!iss.get(ch)) break; // Break the loop if there is no more input
    // TODO: Handle a character (in ch)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top