首页 文章

C编程:基本的fscanf问题与双打

提问于
浏览
0

我在 fscanf 遇到了一些问题 . 我对C很新,但我似乎无法从.txt文件中加载 fscanf 正确的信息 .

int main() {

    //Vars
    FILE *tempFileIn;
    int rowIndex = 0;
    int objectIdNum;
    double magnitudePhotographed;
    double distance;
    int velocity;
    double magnitudeCorrected;
    double magnitudeTotal;

    //Read File Data
    tempFileIn = fopen("hubbleData.txt","r");
    if (tempFileIn == NULL) {
        printf("File read error.");
    }

    printHeaders();
    while(!feof(tempFileIn)) {
        fscanf(tempFileIn, "%lf %lf %lf %lf %lf", &objectIdNum, &distance, &velocity, &magnitudeCorrected, &magnitudeTotal);
        printf( "%2.3f      %2.3f", velocity, distance);
        printf("\n");
        rowIndex++;
    }

    return 0;
}

速度按预期打印,但距离始终打印为0.0000 . 如果我切换两者的打印顺序,将正确打印距离,速度将打印为0.0000 . 我只关心第二和第三列,但必须根据项目指南扫描所有列 .

Input format:
1      0.032    +170      1.5      -16.0
2      0.034    +290      0.5       17.2
6822   0.214    -130      9.0       12.7
598    0.263    -70       7.0       15.1
221    0.275    -185      8.8       13.4
224    0.275    -220      5.0       17.2
5457   0.45     +200      9.9       13.3

Actual Output:                
170.000      0.000
290.000      0.000
-130.000      0.000
-70.000      0.000
-185.000      0.000
-220.000      0.000
 200.000      0.000

Expected Output:
170.000      0.032
290.000      0.034
-130.000      0.214
-70.000      0.263
-185.000      0.275
-220.000      0.275
 200.000      0.45

4 回答

  • 0

    你需要3个变化

    1)将 velocity 声明为 double .

    2)在 fscanf 中, objectIdNum 应该被理解为 %d 而不是 %lf .

    最后在从main(退出程序)返回之前使用 flose(tempFileIn); .

    注意:我假设 velocitydouble 因为实际 velocityreal 数字而不是 integral 值 .

  • 0

    velocity 声明为 int ,但在 fscanf()printf() 调用中使用 double . 你可能也想把它声明为 double .

  • 2

    编辑:我在用户发布速度和距离类型之前发布了此评论 . 我假设速度和距离是不兼容的浮点型,而不是整数 .

    试试这个:

    printf( "%2.3f      %2.3f", (float)velocity, (float)distance);
    

    我的猜测是你将变量传递给printf,它们与浮点数的大小不同,因此打印“velocity”的第二部分而不是距离 . Printf使用堆栈来传递变量,函数没有定义变量的数量和大小,因此任何大小不匹配都会导致这样的问题 .

  • 1

    objectIdNumvelocity 声明为 double ,以便 fscanfprintf 可以正常工作 .

    你声明变量 velocityint 并在 fscanfprintf 中使用了错误的格式说明符

相关问题