文字列として渡される特定の分数式からトークンを抽出したいのですが、
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;
}
}
この Web サイト: http://www.cplusplus.com/reference/string/string/は、文字列関数に関する情報を提供します。
コードを変更して再度実行すると、次のような出力が得られます。
Number: -5
Operator: *
Fraction: 7 over 27