功能无法正确地将数据读入数组

时间:2013-05-07 04:24:34

标签: c arrays

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

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
}

2 个答案:

答案 0 :(得分:1)

在循环中首先重置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
}

答案 1 :(得分: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
}