Convert char array to a int number in C

前端 未结 5 1077
梦毁少年i
梦毁少年i 2020-11-30 01:32

I want to convert a char array[] like:

char myarray[4] = {\'-\',\'1\',\'2\',\'3\'}; //where the - means it is negative

So it should be the

5条回答
  •  孤独总比滥情好
    2020-11-30 01:39

    So, the idea is to convert character numbers (in single quotes, e.g. '8') to integer expression. For instance char c = '8'; int i = c - '0' //would yield integer 8; And sum up all the converted numbers by the principle that 908=9*100+0*10+8, which is done in a loop.

    char t[5] = {'-', '9', '0', '8', '\0'}; //Should be terminated properly.
    
    int s = 1;
    int i = -1;
    int res = 0;
    
    if (c[0] == '-') {
      s = -1;
      i = 0;
    }
    
    while (c[++i] != '\0') { //iterate until the array end
      res = res*10 + (c[i] - '0'); //generating the integer according to read parsed numbers.
    }
    
    res = res*s; //answer: -908
    

提交回复
热议问题