0

我一直在尝试从文件中获取数据并将其存储在数组中,但是这段代码似乎不起作用。文本文件如下所示:

KNIFE JACK          1.3 6.0 5.1 6.3 5.9 6.5
WILLIAMSON FLIP A   1.4 3.5 4.1 4.7 7.2 3.8
SOMMER TODD         1.2 8.0 9.1 8.1 9.3 9.0
SWAN MIKE           1.1 4.3 2.1 9.9 6.2 7.0

我在函数“getData”中编写了代码。这里是:

int getData(FILE* fpIn, char nom[][LEN], float diffFactor[], float scores[][5])
{
    int i = 0;
    int j;
    int tempCh;

    while (i < MAX && fscanf(fpIn,"%c", &nom[i][0])!=EOF) {
        while(j < LEN && (tempCh = fgetc(fpIn)) != '\n') {
            if (tempCh != '\n')
                nom[i][j] = tempCh;
            j++;
        }
        i++;
    } //while i

    return i; //number of divers
}
4

2 回答 2

1

在第一个 while 循环中重置 j 的值。

int getData(FILE* fpIn, char nom[][LEN], float diffFactor[], float scores[][5])
{
    int i = 0;
    int j;
    int tempCh;
    while (i < MAX && fscanf(fpIn,"%c", &nom[i][0])!=EOF) {
        j = 1;
        while(j < LEN && (tempCh = fgetc(fpIn)) != EOF) {
            if (tempCh != '\n') {
                nom[i][j] = tempCh;
                j++;
            }
            else
                break;
        }
        i++;
    } //while i

    return i; //number of divers
}
于 2013-05-07T04:49:08.953 回答
0

大概是这样的:

#include <string.h>
#include <ctype.h>

char *trimEnd(char *str){
    char *p;
    if(str == NULL || *str == '\0') return str;
    p=str+strlen(str);
    while(isspace(*--p) && p >= str){
        *p = '\0';
    }
    return str;
}

int getData(FILE* fpIn, char nom[][LEN], float diffFactor[], float scores[][5]){
    char buff[LEN];
    int i = 0;
    while (i < MAX && EOF!=fscanf(fpIn, "%[^0-9]%f %f %f %f %f %f", buff,
                                        &diffFactor[i],
         &scores[i][0],&scores[i][1],&scores[i][2],&scores[i][3],&scores[i][4]))
    {
        strcpy(nom[i], trimEnd(buff));
        i++;
    } //while i

    return i; //number of divers
}
于 2013-05-07T10:49:42.033 回答