#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(viod)
{
char guesture[3][10]={"scissor","stone","cloth"};
int man,computer,result,ret;
srand(time(NULL));
while(1){
computer=rand()%3;
agin:
printf("Input your gusture(0-scissor 1-stone 2-cloth):");
ret=scanf("%d",&man);
if(ret!=1 || man<0 || man>2){
printf("Invalid input,plese input agin!\n");
goto agin;
}
printf("Your gusture :%s\t Computer's gusture:%s\n",guesture[man],guesture[computer]);
result=(man-computer+4)%3-1;
if(result>0)
printf("You win!\n");
else if(result==0)
printf("Draw!\n");
else
printf("You lost!\n");
}
return 0;
}
~
正常輸出如下:

但當輸入字符是回一直重復agin陳述句:
uj5u.com熱心網友回復:
輸入如3.2、de、f等任意非整數時會出現如上錯誤uj5u.com熱心網友回復:
是scanf非法輸入時、下次回圈直接使用快取區資料造成,可參考這個文章https://blog.csdn.net/yong_ss/article/details/79260815?utm_source=blogxgwz0
uj5u.com熱心網友回復:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//int main(viod)
int main(void)
{
char guesture[3][10]={"scissor","stone","cloth"};
int man,computer,result,ret;
srand(time(NULL));
while(1){
computer=rand()%3;
agin:
printf("Input your gusture(0-scissor 1-stone 2-cloth):");
ret=scanf("%d",&man);
if(ret!=1 || man<0 || man>2){
printf("Invalid input,plese input agin!\n");
while (getchar() != '\n')
;
goto agin;
}
printf("Your gusture :%s\t Computer's gusture:%s\n",guesture[man],guesture[computer]);
result=(man-computer+4)%3-1;
if(result>0)
printf("You win!\n");
else if(result==0)
printf("Draw!\n");
else
printf("You lost!\n");
}
return 0;
}
供參考~
原因是輸入的不匹配%d的資料時,ret會回傳0,但是上次輸入的內容還在輸入快取里,你需要把這個錯誤的輸入從輸入快取里去掉,否則,下次的scanf會自動匹配上次輸入的錯誤內容,所以一直在列印錯誤輸入;
解決辦法就是用getchar()去掉;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/224629.html
標籤:C語言
