我正在查看包含单词和数字的数据文件,我需要从每行中取出数字并将它们存储在数组中。
Cheryl 2 1 0 1 2 0
Neal 0 0 2 0 2 0
Henry 0 2 2 0 2 0
Lisa 0 0 0 0 2 1
这是文件格式化的方式。我首先将每一行输入一个数组participants[]
,然后我需要从每一行中取出数字并将它们分别放在一个单独的二维数组中。即第一行将被翻译为:
responses[0][0] = 2
responses[0][1] = 1
responses[0][2] = 0
responses[0][3] = 1
responses[0][4] = 2
responses[0][5] = 0
此时,我使用char *pointer = strstr(" ", participants[]);
检测到第一个空格,并且能够使用strcpy(temp, pointer+1);
找到数字的开头。
从那时起,我遇到了问题,因为我很难将数字串(仍为char
字符串)转换为单独的整数值,以存储在我的responses[][]
数组中。
谢谢!
答案 0 :(得分:1)
如果这是完全格式,那么fscanf
/ sscanf
可能会为您完成这项工作吗?即
#include <stdio.h>
int main(void)
{
int nums[6];
char line[] = "Cheryl 2 1 0 1 2 0";
sscanf(line, "%*s %d %d %d %d %d %d", &nums[0], &nums[1], &nums[2], &nums[3], &nums[4], &nums[5]);
printf("%d %d %d %d %d %d\n", nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]);
return 0;
}
输出:
2 1 0 1 2 0
然后只需检查返回值以确保读取了正确数量的数字。
编辑:对于任意数量:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strchr_ignore_start(const char *str, int c)
{
if (c == '\0') return strchr(str, c); /* just to be pedantic */
/* ignore c from the start of the string until there's a different char */
while (*str == c) str++;
return strchr(str, c);
}
size_t extractNums(char *line, unsigned *nums, size_t num_count)
{
size_t i, count;
char *endptr = line;
for (i = 0, count = 0; i < num_count; i++, count++) {
nums[i] = strtoul(line, &endptr, 10);
if (line == endptr) /* no digits, strtol failed */
break;
line = endptr;
}
return count;
}
int main(void)
{
unsigned i, nums[9];
char line[] = "Cheryl 2 1 0 1 2 0 0 1 2";
char *without_name;
/* point to the first space AFTER the name (we don't want ones before) */
without_name = strchr_ignore_start(line, ' ');
printf("%u numbers were successfully read\n",
(unsigned)extractNums(without_name, nums, 9));
for (i = 0; i < 9; i++)
printf("%d ", nums[i]);
putchar('\n');
return EXIT_SUCCESS;
}
答案 1 :(得分:0)
strtok()
似乎是一个明显的解决方案:
char buf[1024];
int y;
for(y=0;fgets(buf, sizeof buf, file); y++){
strtok(buf, " "); //burn name;
char *str;
int x = 0;
for(str=strtok(NULL, " "); str; str=strtok(NULL, " ")){
responses[y][x++] = atoi(str);
}
}