gpt4 book ai didi

将一段字符数组更改为C中的整数数组

转载 作者:太空宇宙 更新时间:2023-11-04 04:04:15 24 4
gpt4 key购买 nike

我正在查看一个包含单词和数字的数据文件,我需要从每一行中取出数字并将它们存储在一个数组中。

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[][ 中的单个整数值] 数组。

谢谢!

最佳答案

如果那是您的精确 格式,那么也许 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;
}

关于将一段字符数组更改为C中的整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8058156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com