随机猜谜游戏 - 错误 [英] Random guessing game - bug
本文介绍了随机猜谜游戏 - 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这个code的一个问题,当我进入,而不是整数的字符串。如何检查用户是否entred一个字符而不是整数? (我想摆了个消息给用户说,你应该使用数字,而不是字符)
另外:如果你发现在这个code什么可以改善,请帮帮我! (我是新的C)
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&time.h中GT;
诠释主(){ INT秘密的答案; 函数srand((无符号)时间(NULL)); 秘密=兰特()%10 + 1; 做{
的printf(猜1和10之间的数字);
scanf函数(%d个,&安培;回答);
如果(秘密<答案)看跌期权(猜猜更高的价值);
否则,如果(秘密>的答案)看跌期权(猜一个较低的值);
}而(秘密=答案!); 看跌期权(Congratz!);
返回0;
}
解决方案
scanf函数返回匹配的数量是发现。在你的情况下,它会返回 1
如果readss一个数字。 0
,如果它不能读取一个数字:
如果(scanf函数(%d个,&安培;!答案)= 1){
看跌期权(请输入一个数字); //现在在标准输入的其余部分阅读并把它扔掉。
焦炭CH;
而((CH =的getchar())='\\ n'和;!&安培; CH = EOF!); //跳到do while循环的下一个迭代
继续;
}
I have a problem in this code when I enter a string, instead of integer. How do I check if the user has entred a character instead of integer? (I would like to put out a message to the user saying you should use numbers, not characters)
ALSO: if you find anything in this code I can improve, please help me! (I am new to C)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main () {
int secret, answer;
srand((unsigned)time(NULL));
secret = rand() % 10 + 1;
do {
printf ("Guess a number between 1 and 10");
scanf ("%d",&answer);
if (secret<answer) puts ("Guess a higher value");
else if (secret>answer) puts ("Guess a lower value");
} while (secret!=answer);
puts ("Congratz!");
return 0;
}
解决方案
scanf returns the number of matches is finds. In your case it will return 1
if it readss a number. 0
if it can't read a number in:
if(scanf ("%d",&answer) != 1){
puts("Please input a number");
// Now read in the rest of stdin and throw it away.
char ch;
while ((ch = getchar()) != '\n' && ch != EOF);
// Skip to the next iteration of the do while loop
continue;
}
这篇关于随机猜谜游戏 - 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文