简体   繁体   中英

Reading Numbers from a .dat file with numbers arranged columnwise into an array in C

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

int main()
{
     int block[100];
     int i = 0;

     FILE *fp;

     fp = fopen("blockage.dat","r");

     if (fp != NULL){
     while( !feof(fp) )
     {
         fscanf(fp,"%d",&block[i++]);
     }
     }
     fclose(fp);

     return 0;

}

My blockage.dat file looks like this:

3.712e+05
4.265e+05
5.345e+05
....

The numbers are arranged row wise. So my C program is stuck in the first loop itself. How do I sort this ? How do I ensure that it goes to the next line ?

Where is i declared in your program?

Set i to 0.

int i = 0;

The file contains floating type data. So your array should be

float block[100];

Then do

while((fscanf(fp,"%f",&block[i++])) != EOF);

Depending on the values which you are reading you declare your array with double or long double type.

The problem has nothing to do with arrangement; you are trying to read floats into integer variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM