从txt文件中获取名称和数字所需的建议

时间:2013-03-23 01:19:21

标签: c

我正在编写一个程序,它从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 

2 个答案:

答案 0 :(得分:0)

使用strtok从文件中生成令牌,在换行符和空格上拆分,然后检查每个字符串是否为数字,尝试解析它,使用itoa或类似的东西,如果可解析的话添加到数字否则为名称。

答案 1 :(得分:0)

要以请求的格式存储数据,您需要一个2D数组来存储您的值。由于参与者的数量不熟悉,您必须动态分配所需的空间并在以后释放它。请在下面找到代码的返工版本

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

}