使用sscanf

时间:2020-04-08 22:07:33

标签: c arrays struct scanf fgets

概述:

以下程序尝试使用float从输入文件中的每行扫描5个sscanf值到结构数组中。如果在sscanf的某行中缺少某个值,则程序应检测到该丢失的值并为其分配值1.500,但此替换步骤无效。

输入文件如下所示(请注意第二行的第三个值丢失了):

0.123f, 0.234f, 0.345f, 0.456f, 0.567f
1.123f, 1.642f, , 1.456f, 1.567f
1.678f, 1.789f, 1.891f,1.911f, 2.001f

预期的输出(请注意第二行中的第三个值已被替换为1.500 ):

0.123, 0.234, 0.345, 0.456, 0.567
1.123, 1.642, 1.500, 1.456, 1.567
1.678, 1.789, 1.891, 1.911, 2.001

实际输出(无法正常工作):

0.123 0.234 0.345 0.456 0.567
1.123 1.642 -431602080.000 -431602080.000 -431602080.000
1.678 1.789 1.891 1.911 2.001 

当前尝试:

#include "stdio.h"

int main() {

    typedef struct {
        float x, y, vx, vy, mass;
    }DATA;

    FILE *file = fopen("null_detector.nbody", "r");
    if (file == NULL)
    {
        printf(stderr, "ERROR: file not opened.\n");
        return -1;
    }
    int Nbodies = 3;
    DATA* data = malloc(Nbodies * sizeof * data); // Allocation for array of structs
    char line[256];
    int i;
    for (i = 0; i < Nbodies; i += inc)
    {
        fgets(line, sizeof(line), file);

        // Scan 5 float variables per line (this works fine)
        sscanf(line, "%ff, %ff, %ff, %ff, %ff", 
            &data[i].x, &data[i].y, &data[i].vx, &data[i].vy, &data[i].mass);

        // Check if any of the above scanned vars are NULL.
        // Used individual IF statements instead of IF/ELSE to cover
        // multiple NULL occurrences per line
        float substitute = 1.500;
        if (&data[i].x == '\0') { data[i].x = substitute; }
        if (&data[i].y == '\0') { data[i].y = substitute; }
        if (&data[i].vx == '\0') { data[i].vx = substitute; }
        if (&data[i].vy == '\0') { data[i].vy = substitute; }
        if (&data[i].mass == '\0') { data[i].mass = substitute; }
    }

    // Print the contents of array of structs to check for correct output
    for (i = 0; i < Nbodies; i++)
    {
        printf("%.3f %.3f %.3f %.3f %.3f\n", data[i].x, data[i].y, data[i].vx, data[i].vy,     data[i].mass);
    }

    return 0;
}

摘要:

谁能看到为什么这行不通?我认为IF之后的各个sscanf语句将成功地用丢失的值替换1.500。看来此方法可以至少检测到何时缺少值,但是不能用1.500来代替丢失的值。

0 个答案:

没有答案