c++ - 如何将字符符号作为 Action 数学的字符?

标签 c++ math char substitution

我的程序将表达式缩减为一个值。 我在将“字符符号”更改为 Action 字符时遇到问题。你能告诉我一些简单的解决方案或想法如何去做吗?

我试过:

(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;
}

最佳答案

您不能用用户给定的符号替换运算符或函数名,因为编译器必须知道应该调用哪个函数,而且没有将“+”字符转换为的机制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...
}

关于c++ - 如何将字符符号作为 Action 数学的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10165173/

相关文章:

c++ - 如何在函数中返回指针数组?

c++ - openGL光线拾取

python - 第四导数 - 我的图表是错误的,请让我知道我的错误

c++ - 可分离核的卷积

c++ - 从 char 到 string 的无效转换

c++ - 我必须手动解构所有对象吗

c++ - 使用A4音调扩展.WAV文件

python - 如何将积分放入 python/matplotlib 的函数中

C++ char 类型值由操作系统定义?

arrays - MATLAB - 将数字字符数组转换为数字整数数组/矩阵?