有没有办法让我的程序将字符转换为整数?

有没有办法让我的程序将字符转换为整数?

问题描述:

我一直在运行这个并输入“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); 
} 
+0

查找'的atoi'功能 – cmd 2013-04-29 18:09:33

+0

可能重复(HTTP://计算器.COM /问题/ 16272830 /罐I-不知何故,让 - 我 - 程序到转换的字符到整数) – 2013-05-25 09:34:53

你可以做这样的事情:[?我可以以某种方式得到我的程序字符转换为整数]

char ch='d'; //ch is the character to convert 
int i=1+(ch-'a');