gpt4 book ai didi

c - fscanf 转 int 和数组

转载 作者:行者123 更新时间:2023-11-30 16:25:13 25 4
gpt4 key购买 nike

我正在接收一个文件作为 C 程序中的参数

每一行都有不同数量的整数,如下所示:

1 2 4 5 6
7 8 8 9 10 -1 2 3
12 3 4 -2 2 -3 9 2 4

我想将每行的前 2 个参数放入某个 int 中,并将所有其余参数放入一个数组中,对于第 2 行来说,如下所示:

int a;
int b;
int c[10];

int a = 7;
int b = 8;
int c = [8,9,10,-1,1,2,3]

我能够获得前 2 个,但我无法使其在数组中发生。

如有任何帮助,我们将不胜感激

这就是我现在拥有的:

//get line per line until \n
while (fscanf(fp, "%d %d", a, b) != EOF)
while (fscanf(fp,"%d [^\n]", c[n]) != EOF)
n++;

// print each line
for ( int k = 0 ; k < 10; k ++)
printf("%d %d %d \n", a, b, c[k]);

最佳答案

阅读C read file line by lineHow to extract numbers from string in c? ,然后你会得到这样的结果:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(void) {
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;

fp = fopen("input.txt", "r");
if (fp == NULL)
return -1;

while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu:\n", read);
//printf("%s", line);
char* p = line;
int a, b, c[10], counter = -2;
while (*p) { // While there are more characters to process...
if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
// Found a number
long val = strtol(p, &p, 10); // Read number
//printf("%ld\n", val); // and print it.
if(counter == -2)
a = val;
else if(counter == -1)
b = val;
else if(counter < 10)
c[counter] = val;
counter++;
} else {
// Otherwise, move on to the next character.
p++;
}
}
printf("a = %d, b = %d\n", a, b);
for(int i = 0; i < counter; ++i)
printf("%d ", c[i]);
printf("\n");
}

fclose(fp);
if (line)
free(line);
return 0;
}

输出:

Retrieved line of length 10:
a = 1, b = 2
4 5 6
Retrieved line of length 18:
a = 7, b = 8
8 9 10 -1 2 3
Retrieved line of length 21:
a = 12, b = 3
4 -2 2 -3 9 2 4

关于c - fscanf 转 int 和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53472870/

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