读取文件整数和浮点数以将它们存储在二维数组中

时间:2015-11-28 03:40:51

标签: c arrays multidimensional-array file-processing

我想读取文件整数和浮点数,然后我想将它们存储在二维数组中。

假设我有一个包含两列的文件。第一列整数,第二列浮点数。假设我有20行

定义SIZE 100 // 100个条目(文件上100行)

定义SENSORN 10

这是我的代码:

FILE *fptr;
char filename[100];

char dummy1[1];//dummy character that help me to erase what is the buffer when using gets()
int numberOfSensors;
int time[SENSORN][SIZE];
float powerConsumption[SENSORN][SIZE];

int sensor_num;
int count1 = 0;

printf("Please enter the number of sensors: ");
scanf("%d", &numberOfSensors);

//Asking for the link 
//numberOfSensors - 1 because for example, if we want only 2 sensors we need sensor0 and sensor1 only
for (sensor_num = 0; sensor_num <= (numberOfSensors - 1); sensor_num++)
{
    printf("Please enter the file location for sensor %d\n", sensor_num);
    printf("NOTE: use double backslashes to enter file location \n");

    gets(dummy1);//clearing the buffer
    gets(filename);

    fptr = fopen(filename, "r");

    //if file cannot be opened, then display and error message
    if (fptr == NULL)
    {
        printf("Error opening the file! %s \n", filename);
        printf("Please restart the program \n");
        return 0; //exit the program
    }

    else
    {
        //Loop that let us read and print all the file by storing each value to its respective array
        while (!feof(fptr))
        {
            //storing all the values in their respective array
            //sensor_num is the sensor number
            //count1 is the line number we are reading from the file
            fscanf(fptr, "%d %f", &time[sensor_num][count1], &powerConsumption[sensor_num][count1]);

            //making sure we have all the values stored
            //Note: do not comment the following line in order to check that all values are stored
            fprintf(stdout, "%d %6.2f \n", time[sensor_num][count1], powerConsumption[sensor_num][count1]);
            count1++;
        }
    }
}

看起来它正在读取我的文件,但是当我调试它时,它只在我的数组上存储垃圾。有人能解释我这有什么问题吗?

非常感谢你! :d

0 个答案:

没有答案