我想知道如何存储剪切整数并将其存储到数组或变量中(在本例中为“i”)。所以我的问题是如何将第34和53号存储到i和j。
int main(void) {
char str[80] = "qwerty,34,53";
int i,j;
}
答案 0 :(得分:0)
答案 1 :(得分:0)
有很多方法可以做到这一点,例如
#include <string.h>
int main()
{
char *head;
char str[80] = "qwerty,34,53";
int i;
int j;
head = strchr(str, ','); /* first make head, point to the `,' */
if (head == NULL) /* Check that it was found */
return -1;
/* Now use `strtol()' to extract the integers */
i = strtol(head + 1, &head, 10);
j = strtol(head + 1, &head, 10);
printf("i = %d, j = %d\n", i, j);
return 0;
}
这是有效的,因为strtol()
会在找到非数字字符时停止,而head
最终会指向,
,当然这适用于这个简单的情况,也有可能是,
和值之间的空格,因为strtol()
会忽略它们。