Convert single char to int

后端 未结 3 1970
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-16 21:00

How can I convert char a[0] into int b[0] where b is a empty dynamically allocated int array

I have tried

char a[] = \"4x^0\";
int *b;
b = new int[10         


        
3条回答
  •  半阙折子戏
    2020-12-16 21:48

    You can replace the whole sequence:

    char a[] = "4x^0";
    int *b;
    b = new int[10];
    char temp = a[0]; 
    int temp2 = temp - 0;
    b[0] = temp2;
    

    with the simpler:

    char a[] = "4x^0";
    int b = new int[10];
    b[0] = a[0] - '0';
    

    No need at all to mess about with temporary variables. The reason you need to use '0' instead of 0 is because the former is the character '0' which has a value of 48, rather than the value 0.

提交回复
热议问题