Home > Software design >  Why doesnt this next line run?
Why doesnt this next line run?

Time:12-13

The point of this program is to ensure valid input of two integers between 0 to 2 with a space in between (and strictly nothing else), and then to assign the result of these two integers to variables. For some reason this isn't allowed.

Very basic typecasting has me confused. The print statement %i and %i never runs! I can't see why, even though I've put braces around the part that has "success" labelled. I've tried quite a few things.

#include <stdio.h>
#include <string.h>

int main(void)
{
    int row, column;
    char buffer[100];

    }

    printf("enter 2 values of row | column format \n");
    
    fgets(buffer,100,stdin);
    sscanf(buffer,"%c %c",&row, &column);
    printf("%i %i", row,column);

// only accepts integers between 0 and 2 inclusive
 
    if ((((int)row >=48) && ((int)row <= 50 )) && ((int)column >= 48) && ((int)column <= 50))
        {
        
        printf("success\n");
        printf("%i and %i", atoi(row), atoi(column));

        }
        
    else
        printf("fail\n");


    return 0;
}

CodePudding user response:

Good that OP it trying to validate input.


To accept 2 int:

char dummy;  // Used to detect text after the 2 digits
if (sscanf(buffer,"%d %d %c", &row, &column, &dummy) != 2) {
  puts("Input is not 2 ints");
}

Then test the range

if (row < 0 || row > 2 || column < 0 || column > 2) {
  puts("Outside 0 to 2 range");
}

Additional code needed to detect out-of-range text for an int. Something like the below which limits input to 1 digit each for the int and records the scan offset between the two int to insure some white-space.

int n1, n2;
if (sscanf(buffer,"%n %n %c", &row, &n1, &n2, &column, &dummy) != 2 || n1 == n2) {
  puts("Input is not 2 ints");
}

Save time

Enable all compiler warnings. A good compiler will complain about sscanf(buffer,"%c %c",&row, &column); - "%c" expects an char *, not int *.

CodePudding user response:

Move away from the scanf() family of functions. They are the cause of so many SO questions...

The following should be simple to understand. When you wake up I'd be happy to elaborate on anything you might find perplexing.

#include <stdio.h>
#include <string.h>

int main( void ) {
    printf("enter 2 values of row | column format \n");
    
    char buf[ 100 ];
    fgets( buf, 100, stdin );

    if( buf[3] == '\n' // fgets leaves LF in the buffer
    &&  ('0' <= buf[0] && buf[0] <= '2' )   // limit ASCII digit
    &&  buf[1] == ' '                       // single space between
    &&  ('0' <= buf[2] && buf[2] <= '2' )   // limit ASCII digit
    ) {
        int row = buf[0] - '0', col = buf[2] - '0';
        printf( "success\n%i and %i", row, col );
    } else
        puts( "fail" );

    return 0;
}
  • Related