scanf与空格的问题 #include<stdio.h> #include<ctype.h> #include<stdlib.h> #include<time.h> void main(){ int guess,number,count; char yes='Y'; while(toupper(yes)=='Y'){ srand(time(0)); number=rand()%100; count=0; do{ do{ printf("\n input the number you guess between 1 and 100 \n"); scanf("%d",&guess); }while(!(guess>=1&&guess<=100));
if(guess<number){ printf("the number you guess is lower than the random number"); count++; } if(guess>number){ printf("the number you guess is bigger than the random number"); count++; }
if(count==15){ printf("you have no chance,try again"); exit(0); }
}while(guess!=number);
if(count<=7){ printf("good job"); printf("\n %d\n",count); } else{ printf("\n you have pass this game"); printf("\n %d",count); } printf("\n NEXT?(Y/N): "); scanf(" %c",&yes); }
------解决方案-------------------- 是为刷新缓冲区的类似作用 在前面加一个fflush(stdin)
------解决方案-------------------- #include<stdio.h> #include<ctype.h> #include<stdlib.h> #include<time.h> void main(){ int guess,number,count; char yes='Y'; while(toupper(yes)=='Y'){ srand(time(0)); number=rand()%100; count=0; do{ do{ printf("\n input the number you guess between 1 and 100 \n"); scanf("%d",&guess);// 这里的SCANF用后会在缓存区留有数据当第2次SCANF时,如果缓存区中有数据,会直接读取建议用 fflush(stdin);(头文件)#include<stdio.h> }while(!(guess>=1&&guess<=100));
if(guess<number){ printf("the number you guess is lower than the random number"); count++; } if(guess>number){ printf("the number you guess is bigger than the random number"); count++; }
if(count==15){ printf("you have no chance,try again"); exit(0); }
}while(guess!=number);
if(count<=7){ printf("good job"); printf("\n %d\n",count); } else{ printf("\n you have pass this game"); printf("\n %d",count); } printf("\n NEXT?(Y/N): "); scanf(" %c",&yes); }这里的空格不太明白,如果加上fflush的话,这里的空格有没有,都没有影响