猜数字游戏源码
guess_number.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*** 1~100 ***/
static int randomNumber(){
return 1 + rand() % (100 - 1 + 1);
}
static void gameRunning(){
srand((unsigned int)time(0));
int num = randomNumber();
int answer = 0;
while(1){
printf("Please input your answer: ");
setbuf(stdin, NULL);
int ret = scanf("%d", &answer);
if(ret != 1){
printf("Input error! Please Retry!\n");
continue;
}
if(answer > num){
printf("Your answer is large!\n");
continue;
}
else if(answer < num){
printf("Your answer is small!\n");
continue;
}
else{
printf("Congratulation!\n");
break;
}
}
}
static void gameInit(){
while(1){
int choose = 1;
printf("**********\n");
printf("0.start\nother:exit\n");
printf("**********\n");
setbuf(stdin, NULL);
scanf("%d", &choose);
if(!choose){
gameRunning();
}
else{
printf("exit!\n");
break;
}
}
}
int main(){
gameInit();
return 0;
}
遇到的问题
Linux下刷新输入缓冲区
接口介绍
int fflush ( FILE * stream );
参数:
stream:指向指定缓冲流的FILE对象的指针。
返回值:成功返回0,失败返回EOF并设置错误指示符。
注意:函数主要用在需要立即把输出缓冲区的数据进行物理写入时。
fflush(stdin);为非标准用法。可能有的编译器可以,有的编译器不行。
在VC编译器中可以实现刷新输入缓冲区,gcc编译器则无效。
void setbuf(FILE *stream, char *buf);
参数:
stream:指向标识开放流的FILE对象的指针。
buf:用户分配缓冲区。应该至少BUFSIZE字节长。或者,可以指定空指针以禁用缓冲。
本次遇到的问题是scanf输入格式不匹配内容时,scanf不会进行读取,格式不匹配字符仍然留在输入缓冲区。导致死循环。Linux下fflush(stdin);无效,可以使用setbuf(stdin, NULL);来禁用缓冲解决问题。