【问题标题】:how to read numbers from a file and assign them to what they actually mean如何从文件中读取数字并将它们分配给它们的实际含义
【发布时间】:2015-02-15 00:35:30
【问题描述】:

写一个C程序来

  1. 计算安大略省一系列湖滩的大肠杆菌平均水平
  2. 决定打开或关闭海滩
  3. 为数据文件中包含的所有湖泊和海滩生成一份报告。

对于每个海滩,文件中有一行数据,以下字段由空格分隔 - 湖 ID(整数)、海滩编号(整数)、采样数(整数)和一个实数(双精度)采样代表 100 毫升水中的生物数量。

湖桌

1: Ontario        
2: Erie    
3: Huron       
4: Muskoka   
5: Simcoe

沙滩桌

100: Kew Beach       
101: Sunnyside Beach  
103: Sandbanks   
201: Port Dover  
202: Port Burwell  
203: Crystal Beach   
301: Goderich  
302: Sauble Beach    
303: Kincardine   
401: Muskoka Beach   
501: Sibbald Point   

这是文件数据:

1 100 12 47.7 52.2 45.5 78.7 45.5 33.2 50.4 60.2 48.9 43.3 49.9 50.6     
1 101 9 75.5 53.2 65.1 81.1 44.1 42.2 41.1 39.7 51.1      
2 201 3 56.6 49.7 45.5     
2 202 2 44.4 66.6          
5 501 4 55.5 34.4 66.6 22.2     
4 401 4 33.3 44.4 55.5 66.6        
3 301 3 50.0 51.1 49.8       
3 302 4 77.7 66.6 22.2 33.3      
3 303 3 55.5 55.5 44.0      
1 103 1 13.3    

我知道如何编写代码和语句,但我不知道如何让程序读取文件以及我将如何分配那个特定的数字是安大略湖,或者如何让程序对样本进行平均, 我第一次编程才 2 个月,所以请多多包涵。

【问题讨论】:

  • 使用 SQL 数据库会更简单
  • 请不要在此处发布您的作业问题,而没有表现出任何相关的努力。这很有可能被关闭。
  • 既然您写了“我知道如何编写代码”,请展示您到目前为止所做的工作,并清楚地指出您遇到问题的部分以及到目前为止您尝试过的内容。这将大大增加您获得帮助的机会。
  • 我没有要求任何人为我做作业。这将是非常愚蠢的,因为我也必须参加考试,然后我不会有 stackoverflow.com 在那里帮助我。我正在就我的导师尚未教过的主题寻求帮助,但指定了截止日期这很早,所以我想先行一步。为了让我真正开始编写程序,我需要知道如何从文件中导入数据,然后让程序使用这些数据。这就是我要问的

标签: c arrays file-io


【解决方案1】:

您可以在文件中写入块结构,以将数据保存为二进制。

用于创建结构

struct Lake_table {
    int id;
    char name[length];
};

struct Beach_table {
    int samplings;
    char name[length]
    double samplings_ml;

};

以这种方式用数据初始化结构!

struct Lake_table lakes[] =  {
{1,"Ontario"}
{2,"Erie"}
{3,"Huron"}
{4,"Muskoka"}
{5,"Simcoe"}
};

struct Beach_table beaches[] = {
{100,"Kew Beach",0.0}
{101,"Sunnyside Beach",0.0}
{103,"Sandbanks",0.0}
{201,"Port Dover",0.0}
{202,"Port Burwell",0.0}
{203,"Crystal Beach",0.0}
{301,"Goderich",0.0}
{302,"Sauble Beach",0.0}
{303,"Kincardine",0.0}
{401,"Muskoka Beach",0.0}
{501,"Sibbald Point",0.0}
};

要保存您的结构,请执行此操作!

FILE *file;
const char file_name[] =  "filename.dat";
file = fopen(file_name,"wb");
if (file != EOF) {
    fwrite(beaches,sizeof(struct Beach_table),length,file);

}

让你的结构去做吧!

struct Beach_table beaches;
FILE *file;
    const char file_name[] =  "filename.dat";
    file = fopen(file_name,"rb");
    if (file != EOF) {
        fread(beaches,sizeof(struct Beach_table),length,file);
    }

访问数据,概念与数组、指针相同。祝你好运

【讨论】:

  • 非常感谢你写了这么多,但我认为这是高级的东西,我不知道如何使用
猜你喜欢
  • 1970-01-01
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多