簡體   English   中英

如何從文件中讀取數字直到C中的EOF

[英]How to read only numbers from file until EOF in C

我具有此功能,可以在文本未知的文件(“ 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代替此程序中使用的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

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM