【问题标题】:How to read only numbers from file until EOF in C如何在C中只读取文件中的数字直到EOF
【发布时间】:2017-07-16 06:28:50
【问题描述】:

我有这个函数来查找文件中带有未知文本(“ADS 50 d 15”)的数字的最大值和最小值。它仅适用于文件中的数字,但当有字符时它会停止。

{
    int n;
    int min = INT_MAX, max = INT_MIN;
    int flag = 0;
    rewind(f);

    while (fscanf(f, "%d", &n) != EOF)
    {

        if (ferror(f))
        {
            perror("Error:");
        }
        if (flag == 0)
        {
            min = n;
            max = n;
            flag = 1;
        }
        if (min>n)
            min = n;
        if (max<n)
            max = n;
    }
    printf("\nMax value: %d\nMin value: %d\n", max, min);
}

【问题讨论】:

  • 如果输入与整数不匹配,fscanf 返回 0,而不是 EOF。另请注意,ferror(f) 只能在 fscanf 已返回 EOF 时为真,因此您的 if 永远不会运行。

标签: c function file numbers


【解决方案1】:

fscanf 将在到达文件末尾后返回 EOF。成功扫描整数时将返回 1。如果输入不是整数,它将返回 0,并且必须删除问题输入。

{
    int n;
    int min = INT_MAX, max = INT_MIN;
    int result = 0;
    char skip = 0;

    rewind ( f);
    while ( ( result = fscanf ( f, "%d", &n)) != EOF)
    {

        if (result == 0)
        {
            fscanf ( f, "%c", &skip);//remove a character and try again
        }
        else
        {
            if (min>n)
                min = n;
            if (max<n)
                max = n;
        }
    }
    printf("\nMax value: %d\nMin value: %d\n", max, min);

【讨论】:

    【解决方案2】:

    尝试以下演示程序中所示的方法。您必须使用fscanf 而不是此程序中使用的scanf

    #include <stdio.h>
    #include <ctype.h>
    
    int main( void ) 
    {
        int min, max;
        size_t n = 0;
    
        while ( 1 )
        {
            char c;
            int x = 0;
    
            int success = scanf( "%d%c", &x, &c );
    
            if ( success == EOF ) break;
    
            if (success != 2 || !isspace( ( unsigned char )c ) )
            {
                scanf("%*[^ \t\n]");
                clearerr(stdin);
            }
            else if ( n++ == 0 )
            {
                min = max = x;
            }
            else if ( max < x )
            {
                max = x;
            }
            else if ( x < min )
            {
                min = x;
            }
        }
    
        if ( n )
        {
            printf( "\nThere were enetered %zu values\nmax value: %d\nMin value: %d\n", 
                n, max, min );
        }
    
        return 0;
    }
    

    如果输入看起来像

    1 2 3 4 5a a6 7 b 8
    

    那么输出将是

    There were enetered 6 values
    max value: 8
    Min value: 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-15
      • 2010-09-17
      • 2016-12-22
      • 2020-10-24
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多