簡単な例の入力行: 2 3 + が出力: 5 と終了する RPN 計算機を作成しようとしています。
入力行を取得し、数字をスタックに置き、数字以外を見つけ、それらが演算子であるかどうかをチェックするプログラムが必要です: '+'、'-'、'/'、または '*' であり、それらが演算子である場合スタックの最後の 2 つの数値の計算を計算し、それらの 2 つの数値を削除してから、新しい数値をスタックに追加します。これは、入力行を解析しながら、左から右に進む必要があります。また、シンボルが演算子の 1 つでない場合は、cout に出力する必要があります。
現在、プログラムはコンパイル時に非常に長いエラー コードのリストを画面に表示します。
ここに私が持っているものがあります:
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main()
{
stack<int> num;
string line;
int n,count=0,a,b;
char c;
while (getline(cin,line))
{
for (string::const_iterator it = line.begin(); it != line.end(); ++ it)
{
if (isdigit(static_cast<unsigned char>(*it)))
{
cout << it << endl;
n = (it - 48);
num.push(n);
count++;
}
else if (ispunct(static_cast<unsigned char>(*it)))
{
if (it == '+' || it == '-' || it == '/' || it == '*')
{
cout << "count is " << count << endl;
if (count>1)
{
b = num.top();
num.pop();
a = num.top();
num.pop();
if (it == '+')
{
cout << "+" <<endl;
num.push(a+b);
count--;
}
else if (it == '-')
{
num.push(a-b);
count--;
}
else if (it == '/')
{
if (b != 0)
{
num.push(a/b);
count--;
}
else
{
cout << "division by zero" << endl;
return(0);
}
}
else if (it == '*')
{
num.push(a*b);
count--;
}
else
{
cout << "invalid input" << endl;
return(0);
}
}
else
{
cout << "stack underflow" << c << endl;
return(0);
}
}
cout << c << endl;
}
}
}
while ( !num.empty() )
{
cout << num.top() << endl;
num.pop();
}
return 0;
}