c - fgetc() 无法读取 float

标签 c arrays parsing fgetc

我在使用 fgetc() 时遇到了一个大问题,我无法弄清楚...我尝试解析一个文本文件,所有内容都可以编译,但在执行时我遇到了一个无限循环 xor 一个段错误(Code::blocks ),我的文本文件是这样的:{"USD_EUR": "0.8631364", "EUR_USD": "1.3964719"} 有 16 个汇率变化。我试着把我所有的 float 都放在 rate[16]...

void read(float change[4][4], char* myFile)
{

    FILE* file = NULL;
    file = fopen(myFile, "r+");
    int value,i;
    float rate[16];
    char* str = "";
    if (file != NULL)
    {
        do
        {
            value = fgetc(file);
            printf("%c \n",value);
            while(value > 48 && value < 57)
            {
                value = fgetc(file);
                strcat(str, value);
                //printf("%s \n", str);
            }
            rate[i] = atof(str);
            i++;
            str = "";
        }while(value != EOF);// 125 = }  
        change[0][1] = rate[5];
        change[0][2] = rate[0];
        change[0][3] = rate[15];
        change[1][0] = rate[6];
        change[1][1] = rate[14];
        change[1][2] = rate[7];
        change[1][3] = rate[10];
        change[2][0] = rate[8];
        change[2][1] = rate[2];
        change[2][2] = rate[12];
        change[2][3] = rate[4];
        change[3][0] = rate[3];
        change[3][1] = rate[13];
        change[3][2] = rate[11];
        change[3][3] = rate[9];
        fclose(file);
    }
    else
    {
        printf("Unable to read the file!\n");
    }
}

我也尝试使用 EOF,但我只有数字前的字符然后退出循环 ex: {"USD_EUR": "

最佳答案

我建议您只使用fscanf

例如

FILE *file;
int i = 0, status;
float value;
float rate[16];

file = fopen(myFile, "r");
if(file == NULL){
    printf("Unable to read the file!\n");
    return ;
}
while((status=fscanf(file, "%f", &value))!=EOF){
    if(status==1){
        rate[i++] = value;
        if(i==16)//full
            break;
    } else {
        fgetc(file);//one character drop
    }
}
fclose(file);

关于c - fgetc() 无法读取 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27572242/

相关文章:

c - 在 Netbeans 中观察动态分配的二维数组

c# - 如何让我的按钮在 Unity 中使用 C# 做不同的事情?

c++ - c++字符串数组问题

C# 将一串整数拆分为 IEnumerable<int>

parsing - 获取从正在解析的句子生成的 Prolog DCG 参数

c - 关键字/定义/返回值 - C 中的 "STATUS"?

c++ - 什么是 "pch.h"以及为什么需要将它作为第一个头文件包含在内?

php - PHP 错误消息 "Notice: Use of undefined constant"是什么意思?

html - 如何实现类似 Arc90 的 Readability 或 Instapaper 的 html 页面洗涤器?

c - 如何将两个二维数组中的整数添加到用户指定长度的新二维数组中?