gpt4 book ai didi

c - 从 txt 文件中获取姓名和号码的建议

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

我正在编写一个程序,从 txt 中获取名称和数字,并将它们添加到一个数组中,具体取决于它是字符串还是数字。

我现在的程序是这样的:

#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];

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

for (i = 1; i < participants; i++) {
fscanf(ifp, "%s", name);
for (j = 0; j < 8; j++) {
fscanf(ifp, "%d", &grade[j]);
}
}

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

fclose(ifp);
fclose(ofp);

return 0;
}

我的输出是这样的:

2
Optimus
2686616

我的txt文件是这样的:

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

关于如何让它显示如下的任何想法:

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

最佳答案

要以请求的格式存储数据,您需要一个二维数组来存储您的值。由于参与者的数量是不可知的,您必须动态分配所需的空间并在以后释放它。请找到您的代码的修改版本,如下所示

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

int main()
{
FILE * ifp = fopen("input.txt","r");
FILE * ofp = fopen ("output.txt", "w");
int participants = 0, i , j;
char **name; // Changed the name to a 2D array
int **grade; // Changed the grade to a 2D array
char *curname; // Temp pointer to current name
int *curgrade; // Temp pointer to current array of grades



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

// Allocate memory
name = malloc((sizeof(char *) * participants)); // Allocate pointers to hold strings for the number of participants
grade = malloc((sizeof(int *) * participants)); // Allocate pointers to hold grades for the number of participants

for(i = 0; i < participants; i++) {
name[i] = malloc((sizeof(char) * 10)); //Assumption: Name doesn't exceed 10 characters
grade[i] = malloc((sizeof(int) * 8)); // Assumption: Only 8 grades
}

for (i = 0; i < participants; i++) { /* Fixed: index i should start from 0 */
curname = name[i]; // Get pointer to current name
curgrade = &grade[i][0]; // Get pointer to array of current grades
fscanf(ifp, "%s", curname); // Read name into current name pointer
for (j = 0; j < 8; j++) {
fscanf(ifp, "%d", &curgrade[j]); // Read grades into current array
}
}


printf("%d\n", participants);
for(i = 0; i < participants; i++) {
printf("%s\n", name[i]);
}
for(i = 0; i < participants; i++) {
curgrade = &grade[i][0];
for (j = 0; j < 8; j++) {
printf("%d\n", curgrade[j]);
}
}

fclose(ifp);
fclose(ofp);

for(i = 0; i < participants; i++) {
free(name[i]); // Free the array of individual names
free(grade[i]); // Free the array of grades for every participant
}

free(grade); // Free the grades pointer
free(name); // Free the names pointer

return 0;

关于c - 从 txt 文件中获取姓名和号码的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15582285/

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