将char数组中的char转换为C中的整数

时间:2014-08-10 23:22:32

标签: c

来自像{T,E,S,T,1,2,3,E,N,D}这样的字符数组,我需要从某些位置得到一个整数。以下示例,我想从位置4,5,6获得一个整数。所以,myInt = 123。     我尝试了以下方法,但没有获得所需的整数。

char  receivedata[bytes];

concatVars = concatenate(atoi(receivedata[6] - '0', receivedata[7] - '0');
concatVars = concatenate(concatVars, receivedata[8] - '0');

unsigned concatenate(unsigned x, unsigned y) {
    unsigned pow = 10;
    while(y >= pow)
        pow *= 10;
    return x * pow + y;
}

5 个答案:

答案 0 :(得分:1)

这应该做你想要的:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int arrToInt(char* arr, int len) {
  int toRet = 0;
  for(int i = 0; i < len; i++) {
    if (isdigit(arr[i])) {
      toRet *= 10;
      toRet += arr[i] - '0';
    }
  }
  return toRet;

}

int main(int argc, char* argv[]) {
  char test[] = {'T', 'E', 'S', 'T', '1', '2', '3', 'E', 'N', 'D'};

  int asInt = arrToInt(test, 10);
  printf("Got: %d\n", asInt);
}

输出(使用-std = c99进行编译以使int i = 0内联声明有效):

  

得到:123

答案 1 :(得分:0)

这样做的一种方法是:

int myInt = (((int)myArray[4] - 48) * 100) + (((int)myArray[5] - 48) * 10) + (((int)myArray[6] - 48) * 1);

请注意,48是数字0的ASCII位置,因此通过将字符转换为int然后减去48,您将获得数值。

答案 2 :(得分:0)

标准库的字符串到整数转换函数(例如strtol)一旦到达输入字符序列中的非数字字符就会自动停止。所以你要做的就是告诉这样的功能从哪里开始。在您的情况下,这将执行转换

  const char *s = "TEST123END";

  long myLong = strtol(s + 4, NULL, 10);

  int myInt = myLong;

您只需处理可能的错误。

答案 3 :(得分:0)

这是一种方式:

int myInt = atoi(&myArray[4]);

添加到ced-b的响应,我更喜欢这种语法:

myArray[5] - '0'

也就是说,明确表示你正在减去'0'。

注意:我在字符串中使用了特定的偏移量,因为OP要求:“我需要从某些位置获取一个整数”,我将其解释为字符串中的特定偏移量。基于接受的答案,我似乎已经解释了错误。

答案 4 :(得分:0)

#include <stdio.h>
#include <string.h>

int main(){
    char *str = "TEST123END";
    char s4_6[4] = {0};
    int n;
    memcpy(s4_6, str+4, 3);
    //if(1==sscanf(str, "%*[^0-9]%d", &n))
    //if(1==sscanf(str+4, "%d", &n))
    if(1==sscanf(s4_6, "%d", &n))
        printf("%d\n", n);
    return 0;
}
相关问题