gpt4 book ai didi

c - 使用数组读取文件

转载 作者:行者123 更新时间:2023-11-30 19:15:04 25 4
gpt4 key购买 nike

我想要做的是打开一个文件,读取文件中的信息,向用户询问一系列数据,并计算每个月中属于该范围的天数的百分比。该文件是包含多年来每月每一天的天气数据(温度)的文件。我在使用数组启动程序时遇到困难,并且不确定如何使用数组从文件中获取信息,然后计算并存储我需要的信息。感谢任何帮助,这是迄今为止我的代码:

#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!

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

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.

文件中的示例:

 1             1             2013         63.4
1 2 2013 66.1
1 3 2013 67.2

最佳答案

使用fgets打开文件后读取文件 -

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

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

注意 - 检查 fopen返回值。

关于c - 使用数组读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33147822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com