当我输入字符串而不是整数时,此代码出现问题。如何检查用户是否输入了字符而不是整数? (我想向用户发出一条消息,说你应该使用数字,而不是字符)
另外:如果您在这段代码中发现任何我可以改进的地方,请帮助我! (我是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 返回找到的匹配项数。在你的情况下它会返回1
如果它读取一个数字。0
如果它无法读取以下数字:
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)