2017-02-25 37 views
2

我有此功能可以找到帶有未知文本的文件中的數字的最大和最小值(「ADS 50 d 15」)。它只適用於文件中的數字,但當有字符時,它會停止。如何從文件中只讀取數字,直到C中的EOF爲止

{ 
    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); 
} 
+3

如果輸入不匹配的整數,的fscanf返回0,不'EOF'。還要注意,'ferror(f)'只有在'fscanf'已經返回'EOF'時纔會成立,因此''if'永遠不會運行。 –

回答

2

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

感謝您的幫助!這工作得很好! – user771

3

請嘗試以下方法,因爲它在此演示程序中顯示。您必須使用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 
相關問題