Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.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
C:尝试从文件中读取浮点数形式的字符_C - Fatal编程技术网

C:尝试从文件中读取浮点数形式的字符

C:尝试从文件中读取浮点数形式的字符,c,C,使用gcc在Ubuntu 12.04上运行 我有一个文本文件,其中包含10个值,如下所示: 0020.50 0020.49 0020.47 0020.46 0020.51 0020.50 0020.50 0020.49 0020.49 0020.50 我想在缓冲区中读取这些值,然后对其进行一些计算。所有值都必须视为浮点数 因此,我首先读取缓冲区中的10个字符buffer,然后使用atof()将每个值从字符转换为浮点值,并存储在bufferFloat中。但是我发现bufferFloat没有正确的值

使用gcc在Ubuntu 12.04上运行

我有一个文本文件,其中包含10个值,如下所示:

0020.50 0020.49 0020.47 0020.46 0020.51 0020.50 0020.50 0020.49 0020.49 0020.50

我想在缓冲区中读取这些值,然后对其进行一些计算。所有值都必须视为浮点数

因此,我首先读取缓冲区中的10个字符
buffer
,然后使用
atof()
将每个值从字符转换为浮点值,并存储在
bufferFloat
中。但是我发现
bufferFloat
没有正确的值

这是我的代码:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

using namespace std;

int main()
{
FILE *fp;
int i,x;
int read;

char * buffer;

buffer=(char *)malloc(20);

fp=fopen("Xvalues.txt","r");

read=fread(buffer,1,10,fp);

printf("no. of bytes read %d", read);

float bufferFloat[10];
int j; 

for(j=0;j<10;j++)
{

    bufferFloat[j]=atof(&buffer[j]); //converting characters to buffers 


}

int k;

for (k=0;k<10;k++)
{

    printf("printing buffers as floats: %f \n", bufferFloat[k]);

}

fclose(fp);
return 0;
}
这不是我们存储在文本文件中的内容

请帮我解决这个问题

提前谢谢

这是我使用标记化修改的代码

 #include<stdio.h>
#include<stdlib.h>
#include<math.h>

int main()

{

FILE * fp ;

int read;
int i;

char * buffer;
buffer = (char *)malloc(2000);

fp=fopen("Xvalues.txt", "r");
if(fp==NULL)

{

printf("error reading the file");

}



//storing one line  in  buffer using fgets
if (fgets(buffer, 80, fp)!=NULL){

//    puts(buffer) ;

    }


//Tokanizing 


const char s[2]= " ";

//get the first token  

char * token;
token = strtok(buffer, s);


while (token!=NULL)
{

//printf("%s\n", token);
token  = strtok(NULL, s);

}


//converting to float
float bufferFloat[10000]; 
float ret;
ret =strtof(buffer, bufferFloat); 

for(i=0; i< 10; i++)
{
printf("float values are%f\n", bufferFloat[i]); 
}

fclose (fp);
return 0; 


}

通过执行类似于
在缓冲区中读取10个字符的操作
不会在
缓冲区中为您提供10个
浮点值
[或任何内容]
。这不是读取文件的方式。我的建议是

  • 使用从文件中读取一行

  • 使用适当的分隔符[在您的情况下,可能是空格]标记读取缓冲区

  • 使用(优于
    atof()
    )将每个令牌转换为浮点,并存储到数组中

  • 笔记:

    1.
    fgets()
    读取并存储尾部的
    \n
    。标记化时要小心。 2.
    fgets()
    中提供的缓冲区应该是长的,以保存文件中的完整行输入。

    另外,值得一提的是,请在调用后对
    fp
    进行
    NULL
    检查,以检查
    fopen()
    调用是否成功。这同样适用于
    fread()


    编辑:

    工作代码如下

    #include<stdio.h>
    #include<stdlib.h>
    #include <string.h>
    
    #define MAXVAL 1024
    
    int main()
    
    {
            FILE * fp  = NULL;
            int read = 0;
            int i = 0;
            char * token = NULL;
    
            char buffer[MAXVAL] = {0};
            float bufferFloat[10] = {0}; //better way, use dynamic allocation
    
            fp=fopen("Xvalues.txt", "r");
            if(fp==NULL)
            {
                    printf("error opening the file");
                    return -1;      //don't continue
            }
    
            //storing one line  in  buffer using fgets
            if ( ! fgets(buffer, MAXVAL, fp) ){
                printf("error reading the file");
                return -2;      //don't continue
            }
            //Tokanizing 
            const char *s = " \n";      //because of fgets() stroing \n
            //get the first token  
    
            token = strtok(buffer, s);
            i = 0;
            while (token!=NULL)
            {
                    bufferFloat[i++] = strtof(token, NULL);     //I used NULL used for simplicity, you follow the proper way.
                    token  = strtok(NULL, s);
            }
    
            for(i=0; i< 10; i++)
            {
                    printf("float values are%f\n", bufferFloat[i]);
            }
    
            fclose (fp);
            return 0;
    }
    

    输出:

    [sourav@broadsword temp]$ ./a.out 
    float values are20.500000
    float values are20.490000
    float values are20.469999
    float values are20.459999
    float values are20.510000
    float values are20.500000
    float values are20.500000
    float values are20.490000
    float values are20.490000
    float values are20.500000
    [sourav@broadsword temp]$ 
    

    如果您有您提到的固定号码,您可以使用
    fscanf()

    指南-

    假设-每行10个数字,不会改变

    解决方案

    #include <stdlib.h>
    #include <stdio.h>
    #include <math.h>
    
    
    int main(){
    
    FILE *fp;
    char read;
    
    fp=fopen("Xvalues.txt","r");
    
    
    float array[10];
    
    int i;
    
     do{
        read=fscanf(fp,"%f %f %f %f %f %f %f %f %f %f",&array[0],&array[1],&array[2],&array[3],&array[4],&array[5],&array[6],&array[7],&array[8],&array[9]);
        fclose(fp);
    
        for(i=0 ; i< 10 ;i++){
            printf("%f ",array[i]);
        }
        printf("\n");
    
     }while(read != EOF);
    
     return 0;
    }
    
    #包括
    #包括
    #包括
    int main(){
    文件*fp;
    字符读取;
    fp=fopen(“Xvalues.txt”,“r”);
    浮点数组[10];
    int i;
    做{
    read=fscanf(fp,“%f%f%f%f%f%f%f”、&array[0]、&array[1]、&array[2]、&array[3]、&array[4]、&array[5]、&array[6]、&array[7]、&array[8]、&array[9]);
    fclose(fp);
    对于(i=0;i<10;i++){
    printf(“%f”,数组[i]);
    }
    printf(“\n”);
    }while(read!=EOF);
    返回0;
    }
    
    输出

    20.500000 20.490000 20.469999 20.459999 20.510000 20.500000 20.500000 20.490000 20.490000 20.500000


    如果数据已以浮点形式写入文件,则最好使用fscanf()以适当的格式获取数据。

    使用
    fgets()
    读取行,然后使用
    strod()
    对其进行解析

    <> >任何时候输入数据都在一行中,考虑<代码> fgScript()< <代码> < /p>
    #包括
    #包括
    #包括
    #定义最大预期浮动宽度(7)
    #定义最大预期线宽(n)(n*(最大预期线宽+1)+2)
    int ReadNfloat(文件*stream,浮点*dest,int n){
    char buffer[MAX_EXPECTED_LINE_WIDTH(n)*2];//我喜欢2x个缓冲区
    if(fgets(缓冲区、缓冲区大小、流)==NULL){
    返回-1;
    }
    char*p=缓冲区;
    用于(int i=0;i 9999.99){
    返回i;
    }
    dest[i]=(浮动)编号;
    p=endptr;
    }
    //检测额外垃圾
    while(isspace((无符号字符)*p)p++;
    如果(*p){
    返回-1;
    }
    返回n;
    }
    
    在代码缓冲区中,首先读取10个字符,错误。请在发布时正确地缩进代码。此外,在代码中有一些C++的剩余代码,所以您可以用C++编译器编译C代码。不要这样做。这是两种不同的语言。试试我的解决方案。希望它能起作用。(我使用您的数据集进行了测试)
    //将字符转换为缓冲区
    wut?可以使用类似atof()的方法将字符串转换为浮点值value@Gopi谢谢,但是redundant.OP已经使用了,所以我们可以假设该部分是已知的。:-@Gopi没关系。更新了一个更好的替代方案。:-@SouravGhosh使用了您的方法。请查看我修改过的代码。@user3891236不不,不是一次全部,请逐个执行。另外,
    ret=strtof(缓冲区,缓冲区浮点)
    是错误的。只是一个建议,你不能使用数组吗?警告:
    fscanf()
    family函数不是我的个人爱好。出于许多原因,我想避免使用它们。不要忘记检查
    fscanf()
    的retur值是否成功(通过使用
    read
    变量,您已经成功了一半)。
    gcc test.c --std=c99
    
    ./a.out
    
    [sourav@broadsword temp]$ ./a.out 
    float values are20.500000
    float values are20.490000
    float values are20.469999
    float values are20.459999
    float values are20.510000
    float values are20.500000
    float values are20.500000
    float values are20.490000
    float values are20.490000
    float values are20.500000
    [sourav@broadsword temp]$ 
    
    #include <stdlib.h>
    #include <stdio.h>
    #include <math.h>
    
    
    int main(){
    
    FILE *fp;
    char read;
    
    fp=fopen("Xvalues.txt","r");
    
    
    float array[10];
    
    int i;
    
     do{
        read=fscanf(fp,"%f %f %f %f %f %f %f %f %f %f",&array[0],&array[1],&array[2],&array[3],&array[4],&array[5],&array[6],&array[7],&array[8],&array[9]);
        fclose(fp);
    
        for(i=0 ; i< 10 ;i++){
            printf("%f ",array[i]);
        }
        printf("\n");
    
     }while(read != EOF);
    
     return 0;
    }
    
    #include <stdlib.h>
    #include <stdio.h>
    #include <math.h>
    
    #define MAX_EXPECTED_FLOAT_WIDTH (7)
    #define MAX_EXPECTED_LINE_WIDTH(n)  (n * (MAX_EXPECTED_FLOAT_WIDTH + 1) + 2)
    
    int ReadNfloat(FILE *stream, float *dest, int n) {
      char buffer[MAX_EXPECTED_LINE_WIDTH(n) * 2];  // I like 2x buffers
      if (fgets(buffer, sizeof buffer, stream) == NULL) {
        return -1;
      }
      char *p = buffer;
    
      for (int i=0; i<n; i++) {
        char *endptr;
        double number = strtod(p, &endptr);
        if (p == endptr) {  // no conversion
          return i;
        }
    
        // Code could do various tests. like to see if in expected range.
        if (number < 0 || number > 9999.99) {
          return i;
        }
    
        dest[i] = (float) number;
        p = endptr;
      }
    
      // Detect extra garbage
      while (isspace((unsigned char) *p) p++;
      if (*p) {
        return -1; 
      }
    
      return n;
    }