gpt4 book ai didi

c - 如何从 .t​​xt 中读取单独的数字/行并将它们输入到 2 个不同的数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:52:39 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,从 .txt 中读取行并将它们输入到 2 个不同的数组。

到目前为止我有这个:

    #include <stdio.h>

int main() {
FILE * ifp = fopen("input.txt","r");
FILE * ofp = fopen ("output.txt", "w");
int participants = 0, i;
char name [10];
float grade [10];
float perc [10];

fscanf(ifp, "%d", &participants);

for (i=1; i<participants; i++) {
fscanf(ifp, "%s", &name);

fscanf(ifp, "%f", &grade);

}

printf( "%d\n", participants);
printf( "%s\n", name);
printf( "%f\n", grade);

fclose(ifp);
fclose(ofp);

return 0;
}

我要阅读的文本是:

    2 
Optimus
45 90
30 60
25 30
50 70
Megatron
5 6
7 9
3 4
8 10

我的问题是它读取了前两行,但在到达数字时停止了。我正在尝试将名称成对地放入一个数组中,并将所有数字成对放入一个不同的数组中。现在我只是想检查我是否正在提取数组中的数字,但它并没有将它们全部提取出来。

这是我得到的输出:

    2
Optimus
0.000000

有什么想法吗?

编辑

这是我修改后的新代码:

    #include <stdio.h>

int main() {
FILE * ifp = fopen("input.txt","r");
FILE * ofp = fopen ("output.txt", "w");
int participants = 0, i , j;
char name [10];
int grade [26];
float perc [26];

fscanf(ifp, "%d", &participants);

for (i=1; i<participants; i++) {
fscanf(ifp, " %s", name);
fscanf(ifp, " %d", grade);

}

printf( "%d\n", participants);
printf( "%s\n", name);
printf( "%d\n", grade[0]);

fclose(ifp);
fclose(ofp);

return 0;
}

我的新输出是:

    2
Optimus
45

编辑 2

稍后我需要对这些数字做的是将一行中的第一个数字与同一行中的第二个数字相除,然后乘以 10,然后让它根据数字显示“*”。所以它会像这样打印出来:

    Optimus
+: *****
-: *****
*: ********
/: *******
Megatron
+: ********
-: *******
*: *******
/: ********

“+”是名字下面的第一行。“-”是同名下的第二行。“*”表示第三个。“/”表示第四个。

最佳答案

这是你的主要问题:

    printf( "%f\n", grade);

您正在尝试将指针打印为 float 。你想要 grade[0]

在这一行中:

    fscanf(ifp, "%f", &grade);

这可行,但不正确。它应该是 &grade[0] 或只是普通的 grade

当然,在您的最终版本中,您需要调整数组下标。您还需要为名称分配更多数组 - 目前只能存储一个数组。

要读入数据,您需要对程序进行大量更改。您可以将 grade 声明为 grade[10][8](假设最多 10 个参与者),并将 8 个整数中的每一个都存储在数组中。像这样的循环会处理它:

   for (i = 0; i < participants; i++) {
fscanf(ifp, "%s", name); // read the name (you need to fix this)
for (j = 0; j < 8; j++) {
fscanf(ifp, "%d", &grade[i][j]); // store each number
}
}

关于c - 如何从 .t​​xt 中读取单独的数字/行并将它们输入到 2 个不同的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15581663/

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