Search code examples
cstringwhile-loopatoi

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


I want to be able to input a character and the program would printf("Invalid entry. \nPlease try again:\n") but I also need to be able to input 0, I do not see why it does not work, the way I have it set up a the moment.

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

Solution

  • atoi() always returns zero if the string does not start with valid decimal digits, so cannot be used to distinguish between invalid input and a valid '0' input.

    Instead use scanf() with the "%d" format specifier and check its return value:

    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 ...
    

    Consider putting the code in a function so you don't have to repeat yourself:

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