【问题标题】:C language, how can I check if a given input is a character or a positive int [duplicate]C语言,如何检查给定的输入是字符还是正整数[重复]
【发布时间】:2018-10-11 19:10:06
【问题描述】:

我想知道如何在这种情况下继续从键盘输入:如果给定的输入是正数,它会继续使用代码如果给定的输入是负数或字母,它必须打印“插入一个正数”,然后再次询问另一个输入,直到它有正确的输入。关于负输入和正输入,我写的代码效果很好,但是当我写信时它会出错。我尝试的检查如下

chk=isalpha(n);
while(!chk || n<0)
{
    printf("Inserire un intero positivo \n");
    scanf("%d", &n);
    chk=isalpha(n);
}
printf("%d\n%d\n", t1, t2);

在这种情况下,如果我输入一个负数,它会正常工作,但如果我输入一个字母,printf 就会循环。我也试过while(isalpha(n) || n&lt;0) 和一堆其他的代码,我会为你跳过。请帮我解决这个问题

【问题讨论】:

  • 你应该检查scanf的返回值。或者完全放弃它以支持fgets
  • 您的问题实际上与 C 无关。它与 scanf 有关。如果您想学习 C,最好的建议是:不要使用 scanf。永远。
  • 您不能使用isalpha 来完成此操作。这将检查 n 的值,如果它是字母字符代码之一,则返回 true。例如,如果用户输入 97,它将返回 true,因为 97 是字母“a”的 ASCII 表示。

标签: c while-loop


【解决方案1】:

您可以检查scanf 的返回值,如果char 返回0,您需要清除缓冲区以停止scanf 使用相同的字符。

例子:

int ret = 0;
do
{
     char c;
     while ((c = getchar()) != '\n' && c != EOF) { } /* to clear the bad characters*/

     printf("Inserire un intero positivo \n");
     ret = scanf("%d", &n);
}while(!ret || n<0);

【讨论】:

  • 但是如果我输入一个字母,printf 就会循环。你的代码也会。
  • @JohnnyMopp 这就是预期的行为。用户应该输入有效的数字。
  • If the given input is a negative number or a letter, it must print "insert a positive number" and then ask again for another input until it has the correct one. 这正是OP的需要。
  • 我猜 Johnny 的意思是 scanf 不会消耗任何输入,所以它会在同一个故障部分反复循环。 ideone.com/m95PAD重试前需要清理坏字符。
  • @EugeneSh。确实如此。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 1970-01-01
  • 2017-10-30
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
相关资源
最近更新 更多