随机猜谜游戏 – 错误

当我输入一个字符串而不是整数时,我在这段代码中遇到了问题。 如何检查用户是否输入了字符而不是整数? (我想向用户发出一条消息,说你应该使用数字,而不是字符)

另外:如果您在此代码中发现任何内容我可以改进,请帮助我! (我是C的新手)

#include  #include  #include  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 (secretanswer) puts ("Guess a lower value"); } while (secret!=answer); puts ("Congratz!"); return 0; } 

scanf返回找到的匹配数。 在你的情况下,如果它读取一个数字,它将返回10如果无法读取数字:

 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; } 

读取输入为字符串( char[]%s ),检查所有字符是( isdigit() )数字(可能允许'+''-'作为第一个字符)并使用atoi()转换为int

当且仅当字符串中的每个字符都是数字时,您应该编写一个返回true的函数,否则返回false。

 char * in_str; int answer; ... sscanf("%s", in_str); if (!is_number(in_str)) { printf("Please put in a number, not a letter"); } else { answer = atoi(in_str); } ... 

您需要实现is_number函数

由于您不能假设用户的输入是整数,因此请使用scanf()接受字符串。 然后尝试使用strtol()转换该字符串; 如果输入不是整数,则返回0

使用fgets将输入作为字符串读取,然后使用strtol检查输入。 与atoi相反的strtol能够进行错误检查。