『小项目』猜数字游戏

猜数字游戏源码

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);来禁用缓冲解决问题。

效果演示

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值