简体   繁体   中英

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

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

In order to run shunting-yard, you're going to want to tokenize your string first. That is, turn 12+4 into {'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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM