2013-03-23 46 views
0

我有其目的是收到由空格分隔数字阵列的功能,并且每次一个数,并将其分配给一个结构的一个变量是这样的:strtok的C和传递参数

typedef struct coo { 
    int x; 
    int y; 
} Coord; 

typedef struct exer { 
    Coord coords[1000]; 
} exercise; 


int coordinates(char *sent){ 
    char * pal; 
    int k=0; 
    pal = strtok (sent," "); 
    while (pal != NULL) 
    { 
     exercise.coords[k].x=*pal; 
     pal = strtok (NULL," "); 
     exercise.coords[k].y=*pal; 
     pal = strtok (NULL," "); 
     k++; 
    } 
    return 1; 
} 

问题是稍后打印的坐标不同于发送给定的坐标。

如果我输入坐标1 2 3 4 5 6,它将给我的坐标49 50 51 52 53

预先感谢您。

+4

http://www.asciitable.com/ – 2013-03-23 00:56:27

+0

我米数比骡子...谢谢先生。 – PablodeAcero 2013-03-23 00:58:33

+0

@Armin http://en.wikipedia.org/wiki/EBCDIC – Sebivor 2013-03-23 01:25:04

回答

6

这是因为你得到的第一个字符的值。您得到的值49是字符'1'的ASCII值。

您必须将字符串转换为数字,例如strtol

+0

给我两个有效的理由,我不应该用'0x30'代替'0',其中一个原因会与使用和必然性相抵触本声明中的“ASCII”。如果这个术语不用于描述*性格价值*,那么做错误的事情就会少得多。 – Sebivor 2013-03-23 01:30:37

+0

@modifiablelvalue OP要求正常的整数值不是字符串,所以编码并不重要(它恰好是ASCII),只是转换为整数。 – 2013-03-23 01:38:12

+0

如果编码不相关或不重要,那为什么要提到编码?为什么不提这是一个*字符值*,而是? – Sebivor 2013-03-23 02:15:38

0

详细阐述Joachim Pileborg的回答,pal是一个指向角色的指针。 *pal是一个char,它是一个整数值,表示pal指向的字符。 char,是整数的最小可寻址类型。

如果您打算使用strtol,将coords更改为long是最明智的选择,以便类型匹配。好处在于,strtok在这种解析方面非常糟糕,你可以完全抛弃它。

typedef struct { 
    long x; 
    long y; 
} Coord; 

/* returns the number of coordinates read. */ 
size_t read_coordinates(char *str, Coord destination[], size_t capacity); 

int main(void) { 
    #define EXERCISE_CAPACITY 1000 
    Coord exercise[EXERCISE_CAPACITY]; 
    size_t count = read_coordinates("1 2 3 4 5 6", exercise, EXERCISE_CAPACITY); 
} 

size_t read_coordinates(char *str, Coord destination[], size_t capacity) { 
    size_t x; 
    for (x = 0; x < capacity; x++) { 
     char *endptr = NULL; 
     destination[x].x=strtol(str, &endptr, 10); 
     if (endptr - str == 0) { 
      // Stop when strtol says it can't process any more... 
      break; 
     } 
     str = endptr + 1; 

     destination[x].y=strtol(str, &endptr, 10); 
     if (endptr - str == 0) { break; } 
     str = endptr + 1; 
    } 
    return x; 
} 

如果必须使用int为您的坐标中的类型,这将是明智的使用sscanf的,有点像这样:

typedef struct { 
    int x; 
    int y; 
} Coord; 

/* returns the number of coordinates read. */ 
size_t read_coordinates(char *str, Coord destination[], size_t capacity); 

int main(void) { 
    #define EXERCISE_CAPACITY 1000 
    Coord exercise[EXERCISE_CAPACITY]; 
    size_t count = read_coordinates("1 2 3 4 5 6", exercise, EXERCISE_CAPACITY); 
} 

size_t read_coordinates(char *str, Coord destination[], size_t capacity) { 
    size_t x; 
    for (x = 0; x < capacity; x++) { 
     int n; 
     if (sscanf(str, "%d %d%n", &destination[x].x, &destination[x].y, &n) != 2) { 
      // Stop when sscanf says it can't process any more... 
      break; 
     } 
     str += n; 
    } 
    return x; 
}