繁体   English   中英

从 C 中的文本文件中读取多个数字

[英]Reading multiple numbers from a text file in C

我想要/需要完成的是读取文本文件中的可乘数。

我仍然是编程的初学者,我不确定该怎么做。


这是我的文本文件的样子:

23 35 93 55 37 85 99 6 86 2 3 21 30 9 0 89 63 53 86 79 

这是我的代码的样子:

FILE* infile = fopen("Outputnum.txt", "r");

for(int i=0; i<20; i++){

    fscanf(infile, "%d", &outputnum);
    return outputnum;

}

请记住,我将这段代码放在一个函数中,因为我的主要目标是读取文本文件中的每个数字并记录最小和第二小的数字。 (只有 20 个数字)我认为 for 循环将是解决此问题的最佳方法,但我只返回文本文件中的第一个数字。 (我试图避免使用数组,因为它会使我的终端崩溃)

如果不使用带有硬编码数字限制的循环会更好。 在我的解决方案中,我读取数字直到没有任何数字为止。 您也不希望在循环中使用return语句,因为这会退出当前函数。

#include <stdio.h>
#include <limits.h>

int main()
{
    int smallest = INT_MAX;
    int second_smallest = INT_MAX;
    int number;

    FILE *infile = fopen("numbers.txt", "r");
    if (infile)
    {
        while (fscanf(infile, "%d", &number) == 1)
        {
            if (number < smallest)
            {
                second_smallest = smallest;
                smallest = number;
            }
            else if (number < second_smallest)
            {
                second_smallest = number;
            }
        }
        fclose(infile);
    }

    printf("smallest: %d\n", smallest);
    printf("second smallest: %d\n", second_smallest);
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM