我会尝试在这里解释这个问题。 我编写了这段代码,接受各种类型的输入:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
int main()
{
int number;
printf("press <ENTER> to continue...");
while( getchar() != '\n' );
char *p, s[100];
int n=0;
printf("enter a number: ");
while (fgets(s, sizeof(s), stdin))
{
n = strtol(s, &p, 10);
if (p == s || *p != '\n')
{
printf("Invalid integer, please try again: ");
}
else
break;
}
printf("You entered: %d\n", n);
printf("Enter an integer between 10 and 20: ");
scanf("%d", &number);
while (1)
{
if (number < 10 || number > 20)
{
printf("Invalid value, 10 < value < 20: ");
scanf("%d", &number);
}
else
{
break;
}
}
printf("You entered: %d\n", number);
//part 3
double decpart;
printf("Enter a floating number num: ");
char buf[100];
int len;
char *endptr;
while (1)
{
fgets(buf,sizeof(buf),stdin);
len = strlen(buf)-1;
// right strip spaces (replace by linefeed like fgets ends the input)
while(len>0)
{
len--;
if (buf[len]==' ')
{
buf[len]='\n';
}
else
{
break;
}
}
double floatnum = strtod(buf,&endptr);
if (endptr[0]!='\n')
{
printf("Invalid floating point number, enter again: ");
}
else
{
int intpart = (int)floatnum;
double decpart = floatnum - intpart;
if (decpart == 0.000000){
printf("Invalid floating point number, enter again: ");
}
else
{
printf("Number entered = %.2f\n", floatnum);
break;
}
}
}
double floatnum1;
printf("Enter a floating point number between 10.00 and 20.00: ");
scanf("%lf", &floatnum1);
while (1)
{
if (floatnum1 < 10.00 || floatnum1 > 20.00)
{
printf("Invalid value, 10.000000 < value < 20.000000: ");
scanf("%lf", &floatnum1);
}
else
{
break;
}
}
printf("You entered: %0.2lf\n", floatnum1);
printf("End of tester program for milestone one!\n");
return 0;
}
此代码的第3部分出现问题。我在屏幕上看到输入浮动编号:并立即无需等待用户输入打印无效的浮点数,再次输入:
如果我只是单独运行part3(在代码中作为// part3注释),情况就不是这样了,它运行正常。
任何想法,为什么会这样?