C scanf缓冲区问题#include stdio.h#include time.h#include stdlib.hint getyou()int getcomputer
C scanf缓冲区问题
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int getyou();
int getcomputer();
void charge(int y,int c);
void main(void)
{
int y,c;
printf("\tThis is a game\n");
printf("\t'r': Rock ; 's': Scissors ; 'p': Paper ; 'e': Exit\n");
while(1){
y=getyou();
c=getcomputer();
charge(y,c);
}
}
int getyou()
{
char choice;
int your_choice;
printf("Enter your choice:");
scanf("%c",&choice);
getchar();//这里用getchar()是可以实现循环的,想问一下,还有别的方法吗?缓冲区问题好麻烦,不是很会
switch(choice){
case 'r':
your_choice=0;
printf("You picked Rock, ");
break;
case 's':
your_choice=1;
printf("You picked Scissors, ");
break;
case 'p':
your_choice=2;
printf("You picked Paper, ");
break;
default:
printf("Bye!\n");
exit(0);
break;
}
return your_choice;
}
int getcomputer()
{
int computer_choice;
srand(time(NULL));
computer_choice=rand()%3;
switch(computer_choice){
case 0:
printf("Computer picked Rock.");
break;
case 1:
printf("Computer picked Scissors.");
break;
case 2:
printf("Computer picked Paper.");
break;
defaut:
break;
}
return computer_choice;
}
void charge(int y,int c)
{
if(y==c){
printf("\nThe same,again!\n");
}
else if(y==(c-1)||y==(c+2)){
printf("\nYou win!\n");
}
else{
printf("\nComputer win!\n");
}
}
[解决办法]fflush
[解决办法]fflush 处理stdin 在不同平台行为 不一样 未必行得通
[解决办法]LZ 也可以不去读取缓冲区里面的 \n
可以用
scanf(" %c", &ch);//注意空格
这个语句读取非空白字符[就是不读取空格 tab和回车]
[解决办法]读取缓冲区可以这样
scanf("%*[^\n]");
scanf("%*c");
注意分开写 不要写成了
scanf("%*[^\n]%*c");