所以我正在编写一个程序,从输入文件中读取数据并将其打印出来。
我的任务之一是存储记录总数 (10(,并检查哪个数字重复出现最多。
示例输入文件包含以下内容;
1265 -37.817365 144.968783 6/8/19 10
1726 -37.810009 144.962800 6/8/19 10
1726 -37.809657 144.965221 6/8/19 11
1726 -37.867842 144.976916 6/8/19 14
1328 -37.913256 144.985346 6/8/19 14
1265 -37.822464 144.968863 6/8/19 14
1654 -37.830386 144.979659 9/8/19 11
1726 -37.822464 144.968863 1/9/19 14
1654 -37.817365 144.968783 1/9/19 15
1408 -37.845590 144.971467 1/9/19 16
现在我唯一要检查的数字是第一个值,看看这些数字中哪个出现最多并打印该数字。从这个文件中,它将是编号 1726。
我是阵列和存储的新手,但这就是我目前所拥有的;
int i=0;
int num;
int integers [256];
while(fscanf(stdin, "%d", &num) > 0) {
integers[i] = num;
i++;
}
printf("n%d", num);
我该何去何从?我很困,不知道如何实现我想要的结果。
你可能想要这样的东西:
...
int i=0;
int num;
int integers [256];
char linebuffer[100];
while(fgets(linebuffer, sizeof linebuffer, stdin) != NULL)
{
if (sscanf(linebuffer, "%d", &num) == 1)
{
integers[i] = num;
i++;
}
}
...
这是未经测试的代码,可能会有错误,但你应该明白。特别是如果文件超过 256 行,您可能会遇到数组索引溢出,从而产生未定义的行为。