1

我的程序将表达式减少到一个值。我在将“字符符号”更改为动作字符时遇到问题。你能给我一些简单的解决方案或想法吗?

我试过:

(tab[i]-'0') 'sign' (tab[i+1]-'0'); 

这是完整的代码:

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{

    char* tab = "12+";
    int b = sizeof (tab);
    char* tmp = new char[b] ;
    tmp [b-1] = '\0';

    int k = b/3;

    for(int i=0; i<k; i++){

            if(isdigit(tab[i]) && isdigit(tab[i+1]) ){

               if(tab[i+2]=='+' || tab[i+2]=='-' || tab[i+2]=='*'){
                  char sign = tab[i+2];

                  int n = (tab[i]-'0') + (tab[i+1]-'0');  //here is a problem, i want to replice + as a char sign which will be recognized

                  tmp[i] = n+'0';
               }
               else goto LAB;
            }

            else if (isdigit(tab[i]) && isdigit(tab[i+2])){


            }
            else if (isdigit(tab[i+1]) && isdigit(tab[i+2])){

            }


            else 
            LAB:
            tmp[i]= tab[i];

    }

    cout<<"Import "<<tmp[0]-'0'<<endl;        


    system("PAUSE");
    return EXIT_SUCCESS;
}
4

2 回答 2

0

您不能用用户给出的符号替换运算符或函数名称,因为编译器必须知道应该调用哪个函数,并且没有将“+”字符转换为operator+(int, int)嵌入语言的调用的机制。你必须自己写。

最简单的解决方案是显式编写您想要支持的每个运算符:

int n;
switch(tab[i+2]){
    case '+':
        n = (tab[i]-'0') + (tab[i+1]-'0');
        break;
    case '-':
        n = (tab[i]-'0') - (tab[i+1]-'0');
        break;
    // etc...
}
于 2012-04-15T19:21:59.787 回答
0
int n;
switch(sign){
   case '-': 
      n = (tab[i]-'0') - (tab[i+1]-'0');
      break;
   case '+': 
      n = (tab[i]-'0') + (tab[i+1]-'0');
      break;
   case '*': 
      n = (tab[i]-'0') * (tab[i+1]-'0');
      break;
   default: 
      // handle error here;
      break;
}
于 2012-04-15T19:25:25.190 回答