2013-04-29 2 views
0

나는 이것을 실행하고 표현식으로 "12+"을 타이핑했다. 'm 아래로 가기 값과 다음 값을 추가하려고 노력하고 그 결과를 내게 계속 'c'하지만 3 결과가 필요합니다. 그래서 내 프로그램을 얻을 수있는'C '를 int'3 ' int 4에 char 'd'를하는 식으로? 여기필자의 프로그램에서 문자를 정수로 변환 할 수 있습니까?

//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); 
} 
+0

내가 C/C++을 작성한 이후로 오랜 시간이 걸렸습니다. – basarat

답변

0

당신은 이동 :

int a = (int)'a'; 
int c = (int)'c'; 
int ans = (c-a) + 1 ; // ans will be 3 
+0

어떻게 모든 문자를 숫자로 변환 할 수 있습니까? –

+0

나 자신을 더 잘 설명하기 위해 초기 질문을 편집했습니다. –

1

당신은 단순히 (IT-'0 ') 대신 STK.push의 (IT) STK.push 같은 것을 사용할 수 있습니다.

+0

정확히 무엇을할까요? –

+1

@ 리차드, 죄송합니다. 타이핑에 실수가있었습니다. 나는 그 지위를 편집했다. 변수에 입력 된 문자가 들어 있습니다. 숫자 문자에서 0의 ascii 값을 뺀 다음 각 문자를 숫자로 변환 할 수 있습니다. 따라서 문자 ASCII 코드를 누르는 대신 숫자를 누를 수 있습니다. – oMatrix

관련 문제