我希望能够从给定的分式表达式中提取标记,该表达式作为一个字符串传递。
Fraction s("-5 * 7/27");
当提取的令牌包含单个运算符或数字序列作为操作数时,仅使用stl容器。
请问有人可以指导我如何提取令牌并区分操作数和运算符吗?谢谢。
#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;
}
}
Number: -5
Operator: *
Fraction: 7 over 27
boost::tokenizer
,就能让这个过程更加简单。 - Jesse Good