gpt4 book ai didi

c - 读/写 txt 字符串

转载 作者:太空宇宙 更新时间:2023-11-04 04:38:47 24 4
gpt4 key购买 nike

我正在尝试学习如何在 C 中操作 txt 文件。该程序应读取 population.txt ( http://pastebin.com/Q5fNRuJG ),找到最高人口并显示它,制作一个人口大于 100 万的文件,制作一个包含所有爱尔兰城市的文件,并打印总人口。它只创建空文件,并打印总人口(现在还打印人口最多的城市)。谁能帮忙?

程序(Borland编译):

//Program that filters and processes data with fscanf()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main()
{
FILE *fp;
FILE *ireland;
FILE *mmplus;
int pop;
int highest_pop=0;
char country[50];
char city[50];
int total_pop=0;

fp = fopen("population.txt","r");
ireland = fopen("ireland_pop.txt","w");
mmplus = fopen("greater_than_1MM.txt","w");

//Checking if the file opened correctly
if (fp==NULL)
{
printf("Cannot open file.\n");
exit(1);
}//End if

//Scanning fp row by row
while (fscanf(fp, "%s" "%s" "%i", country, city , &pop) != EOF)
{
//Getting the total population
total_pop=total_pop+pop;

//Storing the highest pop
if (pop > highest_pop)
{
highest_pop=pop;
}//End if

//Finding 1 million+ cities
if(pop>=1000000)
{
fprintf(mmplus,"%s %s %d\n",country,city,pop);
}//End if

//If the city is in Ireland
if (strcmp("ireland",country) == 0)
{
fprintf(ireland,"%s %s %d\n",country,city,pop);
}//End if
}//End while

rewind(fp); //Fix 1

while (fscanf(fp, "%s" "%s" "%d", country, city , &pop) != EOF)
{
//Finding the city with the highest population
if (pop == highest_pop)
{
printf("The city with the highest population is %s, %s, with a population of %d",city, country, pop);
}//End if
}//end while

printf("The total population of all the cities is %d.",total_pop);
getchar();
fclose(fp);
fclose(ireland);
fclose(mmplus);
}

最佳答案

我第一次运行你的程序时得到的是空文件。第二次运行它时,我得到了正确的输出。第三次我得到一个正确的文件和一个错误的文件。

认为我可能输入了ctrl-C 来结束程序。因此,我对程序的最后几行做了一些更改——将 newline 添加到输出中,并在等待输入之前关闭文件。之后,它每次都有效,但我无法解释所有内容。

fclose(fp);
fclose(ireland);
fclose(mmplus);
printf("The total population of all the cities is %d.\n",total_pop);
getchar();
return 0;

关于c - 读/写 txt 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28517389/

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