专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > C语言

scanf与空格的有关问题

发布时间:2011-06-28 16:19:07 文章来源:www.iduyao.cn 采编人员:星星草
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); }

}
对于红线部分,也就是最后一句,我很不明白为什么要在%c前面加一个空格,望高手指点,谢谢

------解决方案--------------------
你前面输入的时候有一个\n留在了输入流中,一个空格是为了把它读掉吧,相当于
fflush(stdin);
------解决方案--------------------
探讨

你前面输入的时候有一个\n留在了输入流中,一个空格是为了把它读掉吧,相当于
fflush(stdin);

------解决方案--------------------
是为刷新缓冲区的类似作用 在前面加一个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的话,这里的空格有没有,都没有影响

}


另外说下: scanf函数中 % 后面,必须带 字符宽度,否者,可以利用它,溢出。

------解决方案--------------------
因为scanf()这个函数是靠回车换行符来返回的
所以回车换行符会留存在缓冲区内,fflush的作用就是刷新缓冲区,使里面得内容得到清空
------解决方案--------------------
回五楼:
C标准并没有规定fflush(stdin)这个stdin参数,你建议的是非标准的,所以楼主的空格法是可移植的.
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: