Home > OS >  How should an input string be read into a shunting yard algorithm calculator?
How should an input string be read into a shunting yard algorithm calculator?

Time:11-25

I have implemented the basic structure of the shunting yard algorithm, but I'm not sure how to read in values that are either multidigit or functions. Here's what I have currently for reading in values:

string input;
getline(cin, input);
input.erase(remove_if(input.begin(), input.end(), ::isspace), input.end());
//passes into function here
for (int i = 0; i < input.length();   i) {
    string s = input.substr(i, 1);
//code continues
}

As you can see, this method can only parse one character at a time, so it is extremely flawed. I also have tried searching up reading in values or parsing them but haven't found a result that is relevant here.

Full Code: https://pastebin.com/76jv8k9Y

CodePudding user response:

In order to run shunting-yard, you're going to want to tokenize your string first. That is, turn 12 4into {'12',' ','4'}. Then you can just use the tokens to run shunting yard. A naive infix lexing algorithm might like this:

lex(string) {
    buffer = ""
    output = {}
    for character in string {
        if character is not whitespace {
            if character is operator {
                append buffer to output
                append character to output
                buffer = ""
            } else {
                append character to buffer
            }
        }
     append buffer to output
     return output
}

Real lexers are a lot more complicated and are a prime field of study in compiler design.

  • Related