3

我想从给定的分数表达式中提取标记,该表达式作为字符串传递,

Fraction s("-5 * 7/27");

提取的标记包含单个运算符或数字序列作为操作数,仅使用 stl 容器。

有人可以指导我这样做吗?我想知道如何提取标记并将操作数与运算符区分开来,谢谢。

4

1 回答 1

3

假设令牌之间总是有空格,下面是如何将它们全部放入队列中:

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

using namespace std;

int main()
{
    stringstream formula("-5 * 7/27");
    string a_token;
    queue<string> tokens; 

    // Use getline to extract the tokens, and then push them onto the queue.
    while (getline(formula, a_token, ' ')) {
         tokens.push( a_token );
    }

    // Print and pop each token.
    while (tokens.empty() == false) {
        cout << tokens.front() << endl;
        tokens.pop();
    }
}

运行程序会输出:

-5
*
7/27

现在要确定哪些是运算符、数字或分数,您可以在循环中执行以下操作:

    if (a_token == "+" || a_token == "-" || a_token == "*" || a_token == "/")
    {
        // It's an operator
        cout << "Operator: " << a_token << endl;
    }
    else
    {
        // Else it's a number or a fraction.

        // Now try find a slash '/'.
        size_t slash_pos = a_token.find('/');

        // If we found one, it's a fraction.
        if (slash_pos != string::npos) {
            // So break it into A / B parts.

            // From the start to before the slash.
            string A = a_token.substr(0, slash_pos);

            // From after the slash to the end.
            string B = a_token.substr(slash_pos + 1);

            cout << "Fraction: " << A << " over " << B << endl;
        }
        else
        {
            // Else it's just a number, not a fraction.
            cout << "Number: " << a_token << endl;
        }
    }

该网站:http ://www.cplusplus.com/reference/string/string/将为您提供有关字符串函数的信息。

修改代码并再次运行后,您将获得如下输出:

Number: -5
Operator: *
Fraction: 7 over 27
于 2012-06-04T04:16:17.523 回答