想要检查输入的值是否为数字。 " isdigit()未按预期在此处工作

时间:2017-12-28 16:33:26

标签: c

我在C中遇到了一个问题。我发布的问题和我在下面写的代码。在这里,我必须在一个数组中输入10个数字,然后我需要检查一个数字出现的次数。但为了验证我输入了一个数字,而不是其他任何东西,我使用了" isdigit()"功能。但这没用。任何人都可以帮我解决它。

/ *     (a)从键盘输入十个数字到一个数组。要搜索的号码是通过     用户的键盘。编写程序以查找数组中是否存在要搜索的数字,如果存在,则显示     它在数组中出现的次数。     * /

    TextInputLayout til = new TextInputLayout(this);
    til.setHintTextAppearance(android.R.style.TextAppearance_Large);

2 个答案:

答案 0 :(得分:2)

不,你不能这样做。 isdigit()应该使用字符,你传递了一个multigit整数变量。

你可以做的就像这样

if( scanf("%d",&a[i])== 1){
  // you can be sure number is entered
}

fflush(stdin)是未定义的行为。

如果你这样做,scanf的使用会更加突出

int clearstdin(){
  int c;
  while ((c = getchar()) != '\n' && c != EOF);
  return (c == EOF);
}

main()

int earlyend = 0;
for(size_t i=0; i<SIZE; i++){
...
... 
    int ret = scanf("%d",&a[i]); 
    while( ret == 0){
         if( clearstdin() ){ /* EOF found */earlyend = 1; break; }
         fprintf(stderr,"%s\n","Entered something wrong");
         ret = scanf("%d",&a[i]);
    }
    if( earlyend ){ /*EOF found*/ }
    if( ret == EOF) { /* Error occured */}
...
}

答案 1 :(得分:0)

%d转换说明符将导致scanf跳过任何前导空格,然后读取一个十进制数字序列,停在第一个非数字字符处。如果输入中没有数字字符(例如,您输入”abc”之类的内容),则输入流中不会读取任何内容,a[i]未更新,scanf将返回0表示匹配失败

所以,你可以做一个像

这样的测试
if ( scanf( “%d”, &a[i] ) == 1 )
{
  // user entered valid input
}

但是...

这并不能完全保护您免受输入错误的影响。假设您输入类似”123abc”的内容 - scanf将读取,转换和分配123并返回1表示成功,将”abc”留在输入流中可能会导致下次阅读。

理想情况下,你想完全拒绝整件事。我个人如下:

char inbuf[SOME_SIZE];  // buffer to store input

if ( fgets( inbuf, sizeof inbuf, stdin ) ) // read input as text
{
  char *chk;                                  // use strtol to convert text to integer
  int temp = (int) strtol( inbuf, &chk, 10 ); // first non-digit character written to chk
  if ( isspace( *chk ) || *chk == 0 )         // if chk is whitespace or 0, input is valid
  {
    a[i] = temp;
  } 
  else
  {
    // bad input
  }
}

这仍然不是100%的解决方案 - 它不能确保用户没有输入比缓冲区更多的字符,但它是朝着正确方向迈出的一步。

坦率地说,C中的输入验证是一种痛苦。