0

私はこれを実行"12+"し、式として入力しています。「一番上の値と次の値を追加しようとしていて、結果'c'が得られ続けますが、結果を3にしたいのです。プログラムでchar 'c'をint '3'に変換する方法はありますか? char 'd' を int 4 などに変換しますか?

//array based stack implementation
class Stack
{
private:
    int capacity;        //max size of stack
    int top;            //index for top element
    char *listArray;       //array holding stack elements

public:
    Stack (int size = 50){ //constructor
        capacity = size;
        top = 0;
        listArray = new char[size];
    }

    ~Stack() { delete [] listArray; } //destructor


    void push(char it) {    //Put "it" on stack
        listArray[top++] = it;
    }
    char pop() {   //pop top element
        return listArray [--top];
    }

    char& topValue() const { //return top element
        return listArray[top-1];
    }

    char& nextValue() const {//return second to top element
        return listArray[top-2];
    }


    int length() const { return top; } //return length



};

int main()
{
    string exp;
    char it = ' ';
    int count;
    int push_length;


    cout << "Enter an expression in postfix notation:\n";
    cin >> exp;
    cout << "The number of characters in your expression is " << exp.length() << ".\n";
    Stack STK;

    for(count= 0; count < exp.length() ;count++)
    {

        if (exp[count] == '+')
        {
          it = exp[count - 1];
          cout << it << "?\n";

              while (!isdigit(it))
        {
            cout << it << "!\n";
            it = exp[count--];
        }

        STK.push(it);
        cout << STK.topValue() << "\n";


        it = exp[count - 2];
        cout << it << "\n";

        if (isdigit(it))
        {
            STK.push(it);

        }
        cout << STK.topValue() << "\n";
        cout << STK.nextValue() << "\n";
        it = STK.topValue() + STK.nextValue();
        cout << it << "\n";

        STK.pop();
        STK.pop();
        STK.push(it);
        cout << STK.topValue() << "\n";

        }


    }
    cout << "The number of characters pushed into the stack is " << STK.length() << ".\n";
    push_length = STK.length();
    return(0);
}
4

2 に答える 2

1

STK.push(it) の代わりに STK.push(it-'0') のようなものを使用できます。

于 2013-04-29T08:07:07.673 に答える
0

どうぞ:

int a = (int)'a';
int c = (int)'c';
int ans = (c-a) + 1 ; // ans will be 3
于 2013-04-29T06:58:49.790 に答える