C++:仅使用STL从字符串中提取记号

3

我希望能够从给定的分式表达式中提取标记,该表达式作为一个字符串传递。

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

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

请问有人可以指导我如何提取令牌并区分操作数和运算符吗?谢谢。


可能是重复问题:如何在C++中对字符串进行分词? - Jesse Good
我检查过了,它们使用空格作为分隔符,但在我的情况下这不起作用。你认为使用string::operator[]来获取每个字符并进行评估是否好? - newbieLinuxCpp
这要看情况。可以假设标记之间会有空格吗? - Daniel Hanrahan
是的,有空格,我需要提取令牌并将其推入队列<string>。 - newbieLinuxCpp
只需使用boost::tokenizer,就能让这个过程更加简单。 - Jesse Good
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

是的先生,我确实这样做了,但对我的情况没有用,因为我需要将操作数与运算符分开,就像这样:- 5 * 7 / 27。 - newbieLinuxCpp
哦,我现在明白了。您想要能够分割分数部分。我会在一分钟内更新帖子,向您展示如何操作。 - Daniel Hanrahan
谢谢,我现在明白了 :D - newbieLinuxCpp
没问题。如果您在计算中使用字符串,那么您可能希望稍后将其转换为数字。您可以这样做:atoi(A.c_str())。 (不要忘记点赞答案!) - Daniel Hanrahan
抱歉打扰了。我很好奇,如果我的表达式中没有空格,那么用空格分隔就不起作用了。我应该怎么办呢?比如说:"1-10*1/(5+2)+9" - newbieLinuxCpp
那会更加困难。您需要构建一个词法分析器/解析器。这方面有很多在线信息。这也可能对您有所帮助:http://www.ibm.com/developerworks/library/j-w3eval/index.html - Daniel Hanrahan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接