2015-10-15 41 views
-1

我想要做的是打开文件,读取文件中的信息,向用户询问一系列数据,然后计算每个月的天数百分比范围。该文件是一个包含一年中每个月每天的天气数据(温度)的文件。我很难用数组启动程序,我不知道如何使用该数组从文件中获取信息,然后计算并存储我需要的信息。任何帮助表示赞赏,这是我到目前为止的代码:使用数组读取文件

#include <stdio.h> 

int main() { 
    int range[12], total[12], i, cold, hot, sum, input, month, day, year; 
    float avg, temp; 
    char filename[20]; 

    printf("Tell me about your preferred temperature for flying:\n"); 
    printf("What is the coldest temperature you can fly in?\n"); 
    scanf("%d", &cold); 

    printf("What is the hottest temperature you can fly in?\n"); 
    scanf("%d", &hot); 

    FILE * ifp = 0; 
    printf("Please enter the name of the weather data file.\n"); 
    scanf("%s", filename); 
    ifp = fopen(filename, "r"); 

    return 0; 
} 

现在我刚刚已经开始完成,我认为是正确的,但我不知道接下来该阵列做才能得到信息不在文本文件中。我不需要完成整个程序,我只需要帮助下一步该做什么。这里的输出应该是什么样子的例子:

Tell me about your preferred temperature for flying: 
What is the coldest temperature you can fly in? 
60 

What is the hottest temperature you can fly in? 
80 

Please enter the name of the weather data file. 
weather.txt 

Month 1: 59.2 percent of days in range. 
Month 2: 69.2 percent of days in range. 
Month 3: 72.6 percent of days in range. 
Month 4: 92.6 percent of days in range. 
Month 5: 98.7 percent of days in range. 
Month 6: 48.3 percent of days in range. 
Month 7: 36.41 percent of days in range. 
Month 8: 18.9 percent of days in range. 
Month 9: 57.64 percent of days in range. 
Month 10: 100.00 percent of days in range. 
Month 11: 65.4 percent of days in range. 
Month 12: 80.5 percent of days in range. 

I recommend month 10 for the flight! 

编辑: 文本文件的格式如下:

1    1    2013   63.4 
1    2    2013   66.1 
1    3    2013   67.2 
+0

首先学习你应该阅读的文件格式,然后从文件中考虑你需要的数据。最后想想你需要真正阅读这些数据的函数,你应该使用'fscanf','fgets'还是其他的? –

+0

分配转储。根本没有实际的核心工作。什么代码非常类似http://stackoverflow.com/questions/33144059/using-arrays-to-read-a-file-and-get-information –

+0

我投票结束这个问题作为题外话,因为家庭作业垃圾邮件。 –

回答

1

使用fgets

The available data is presented in four columns per day: 
MONTH   DAY   YEAR   TEMPERATURE 
The file will end with a -1 on a row by itself. 

从文件实例打开后从文件中读取 -

char data[100]; 
while(fgets(data,sizeof data,ifp)!=NULL){ 
    // get temperature out of array 
    // convert it and store in a variable 
} 

或者如果文件中的数据是固定格式,请使用fscanf

注意 - 检查returnfopen