0

我有一个函数,其目的是接收一个由空格分隔的数字数组,一次一个数字,将它们分配给这样的结构变量:

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

2 回答 2

6

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

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

于 2013-03-23T00:58:09.687 回答
0

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

如果您要使用 strtol,最好将您更改coordslong,以便类型匹配。好处是 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;
}
于 2013-03-23T02:14:09.733 回答