Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用fscanf读取文件的每一行_C_Scanf_Dat Protocol - Fatal编程技术网

使用fscanf读取文件的每一行

使用fscanf读取文件的每一行,c,scanf,dat-protocol,C,Scanf,Dat Protocol,我试图读取.dat文件的每一行,并将其存储在浮点数中。我正在使用fscanf。我的目标是在抽奖后将这些线存储到 #include <stdio.h> int main(void) { char url[]="PREMIOS.dat", nome[20]; float premio[12]; FILE *arq; arq = fopen(url, "r"); if (arq == NULL) { printf("Error\n

我试图读取.dat文件的每一行,并将其存储在浮点数中。我正在使用fscanf。我的目标是在抽奖后将这些线存储到

#include <stdio.h>

int main(void)
{
    char url[]="PREMIOS.dat", nome[20];
    float premio[12];
    FILE *arq;

    arq = fopen(url, "r");
    if (arq == NULL) {
        printf("Error\n");
    } else {
        for(i = 0; i < 12; i++) {
            while((fscanf(arq, "%f\n", &premio[i])) != EOF)
                printf("%.2f\n", premio[i]);
        }
    }
    fclose(arq);
    return 0;
}
由于某种原因,此代码无法存储数字。我怎样才能将这些数字解读为浮动、存储和抽奖后的数字

while (fscanf(arq, "%f\n", &premio[i])) != EOF )
       printf("%.2f\n", premio[i]);
将继续逐行读取文件,直到文件结束。在这种情况下,每次仅覆盖
premio
索引0处的值

相反,你应该尝试一些类似

If ((fscanf(arq, "%f\n", &premio[i])) != EOF )
       printf("%.2f\n", premio[i]);

请整理您的代码,张贴的代码无法编译!1) …:13:13:错误:“i”未声明(此函数中首次使用)2)关于已设置但未使用变量的警告。3) 关于未使用变量的警告。请更正您的代码并对您的问题进行编辑,内容涉及:
while((fscanf(arq,%f\n,&premio[i])!=EOF)printf(%.2f\n,&premio[i])
while()
将从
arq
读取所有内容,并将所有读取的条目放入
premio[0]
。然后立即使范围1…11中的
i
的所有值的
while()
失败,关于:
printf(“错误”)1)错误消息应输出到
stderr
,而不是
stdout
,当错误指示来自C库函数时,还应输出系统认为发生错误的原因文本。建议使用<代码>perror(“URL.data的fopen输入失败”)后接
退出(退出失败)
调用
exit()
是因为在'if/else'代码块之后,当调用
fopen()
失败时,没有打开的文件指针可传递到
fclose()
,因此将发生运行时错误。OT:关于:
char。。。诺姆[20]
该字符数组在发布的代码中不再被引用,那么为什么还要声明它呢?
If ((fscanf(arq, "%f\n", &premio[i])) != EOF )
       printf("%.2f\n", premio[i]);