繁体   English   中英

输入字符以打印错误,但在c中输入0时不输入

[英]Inputting a character to print error, but not when 0 is input in c

我希望能够输入一个字符,程序将输出printf("Invalid entry. \\nPlease try again:\\n")但是我还需要能够输入0,我不明白为什么它不起作用,我将其设置为片刻。

for (i=0; i<*r; i++)
{

    printf("Please enter the number of 1's in row %d :\n", (i+1));
        scanf("%s", &str);

        if(atoi(str)!=sizeof(char))
        {
            while(atoi(str)==0)
            {
                printf("Invalid entry. \nPlease try again:\n");
                    scanf("%s",str);
            }
                f = atoi(str);
        }
        else
        f=0;

        if (f>0)
        {
            printf("Please enter column location of the 1's in row %d : \n", (i+1));

                for (j=0; j<f; j++)
                {
                    scanf("%d", &g);
                        p[i][g-1]= 1;
                }
        }
}

我不明白为什么您不输入整数就可以摆脱将String转换为Integer的麻烦。

int num;
printf("Please enter the number of 1's in row %d :\n", (i+1));
scanf("%d", &num);
while(!num)
{
    printf("Invalid entry. \nPlease try again:\n");
    scanf("%d", &num);
}

如果字符串不是以有效的十进制数字开头,则atoi()始终返回零,因此不能用于区分无效输入和有效“ 0”输入。

而是使用带有“%d”格式说明符的scanf()并检查其返回值:

int i = 0 ;
do
{
    int check = scanf( "%d", &i ) ;
    while( getchar() != '\n' ) ; // flush until end of line
    if( check == 0 )
    {
        printf( "Invalid entry. \nPlease try again:\n");
    }

} while( check == 0 ) ;

// Now work with the valid input integer value in i ...

考虑将代码放入函数中,这样您就不必重复自己了:

int getIntegerInput()
{
    int i = 0 ;
    do
    {
        int check = scanf( "%d", &i ) ;
        while( getchar() != '\n' ) ; // flush until end of line
        if( check == 0 )
        {
            printf( "Invalid entry. \nPlease try again:\n");
        }

    } while( check == 0 ) ;

    return i ;
}

您发现了为什么atoi()不好。 atoi()不会执行任何错误报告,例如整数溢出,无效输入等,并且无法区分有效的0输入和转换失败。

使用strto*l()函数进行转换,因为它们可以检测到转换失败。 您的输入阅读可以按照以下步骤进行:

#include <stdio.h>
#include <stdlib.h>
#include<limits.h>
#include<errno.h>

....

for(;;) {

   scanf("%s", str); 
   errno=0;
   long f = strtol(str, &endp, 0);

   if (endp == str || *endp != 0 || 
      (errno == ERANGE && (f == LONG_MAX || f == LONG_MIN)) || 
      (errno != 0 && f == 0)) {
          printf("Invalid entry. \nPlease try again:\n");
   }
   else  break;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM