使用后继续使用fscanf

时间:2017-10-24 20:39:55

标签: c scanf

我正在尝试在文本文件中给出列数和行数+1之后从文本文件构建矩阵。矩阵用逗号分隔,是双值。

4

3

1.32,4.32,5.6764,5.6545,54.6766

2.32,2.43,4.765,5.453,432.12

3.423,5.34,7.4534,5.3,7.321

int main (int argc, char *argv[]) {
    FILE *train;

    train = fopen(argv[1], "r");

    int abutes,examples;
    fscanf(train," %d %d",&abutes,&examples);  /*scan in number of examples and attributes*/
    printf("%d", abutes);
    printf("%d", examples);

    /*make array using malloc*/

    double ** trainA = NULL;
    int i=0;
    int abuteswp;
    int abuteswp1;
    int j=0;
    abuteswp=abutes+1;

    abuteswp1=abutes+2;
    trainA = malloc( examples * sizeof(double *));

    for(i = 0; i < examples; i++)
    {
        trainA[i] = malloc( abuteswp1 * sizeof(double));
    }
    for(i = 0; i <examples; i++)
    {
        trainA[i] = malloc( examples * sizeof(double));
    }
    for (j = 1; j < examples; j++){
        // read the first value into the 0-th element of the j-th row
        fscanf(train, " %lf", &trainA[j][0]);

        // read remaining values, testing for a comma
        // before each value and discarding it
        for (i = 2; i < abuteswp+1; i++){
            fscanf(train, ",%lf", &trainA[j][i]);
        }
    }

    int p;
    /*add in 1s to matrix*/
    for (p=0;p<examples;p++) {
        trainA[p][0]=1;
    }

    for (j=0;j<examples;j++) {
        for ( i=0; i <abuteswp1; i++) {
            printf("%lf", trainA[j][i]);
        }
    }

    free(trainA);
    return 0;
}

扫描到第4行第2列为什么会停止?

1 个答案:

答案 0 :(得分:0)

第二个不能按预期工作,因为它不包含字段转换说明符。

简而言之:添加百分号。

详细信息:如C++ Reference所述,当scanf()fscanf()等相同)遇到非空格字符时,格式说明符除外(以%开头)标志)它将输入的输入字符与格式字符串中的该字符进行比较;如果它们匹配,则丢弃输入字符并继续扫描下一个字符,否则scanf()失败并返回。

所以你需要按原样读取第一个数字,但在阅读同一行中的每个剩余数字之前,你需要丢弃一个逗号字符:

    for (j = 0; j < examples; j++){
        // read the first value into the 0-th element of the j-th row
        fscanf(train, "%lf", &trainA[j][0]);

        // read remaining values, testing for a comma
        // before each value and discarding it
        for (i = 1; i < abuteswp; i++){
            fscanf(train, ",%lf", &trainA[j][i]);
        }
    }

您可能还想检查fscanf()的返回值,以确保输入文件实际包含正确数量的数据并且符合预期格式