我有这个功能来查找文件中带有未知文本的数字的最大值和最小值(" 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);
}
答案 0 :(得分: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
答案 1 :(得分: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);