scanf() only sign and number

2019-02-24 00:05发布

问题:

I want to get variables sign and number with scanf().
There is how it should works:

 input:
 + 10
 output:
 OK, "sign = +" and "number = 10"

 

 input:
 +10
 output:
 Fail!

 

 input:
 10
 output:
 Fail!

 

 input:
 a
 output:
 Fail!

I've tried this solution, but it doesn't worked for me. Especially for inputs: +10 and a

 plus='+';
 minus='-';     

 if ( scanf(" %c %d", &sign, &number) != 2 || ((sign != minus) && (sign != plus)) || number < 0 ) 
                {
                printf("Fail!");
                } 
            else {...}

Thanks.

回答1:

scanf(" %c %d", &sign &number) != 2 does not work as the format does not require a space between the char and int. A " " matches 0 or more white-space, not a single ' '.


So code needs to look for sign, space and number.

char sign[2];
int number;
if (scanf(" %1[+-]%*1[ ]%d", sign, &number) != 2) {
  puts("Fail");
}

" " Scan and skip optional white-space
"%1[+-]" Scan and save 1 + or -
"%*1[ ]" Scan and do not save a space.
"%d" Scan white-spaces and then an int.


Note: Better to use fgets(), read the line and then use sscanf().


[Edit] More robust solution - it uses fgets() as robust solutions do not use scanf().

  char buf[80];
  if (fgets(buf, sizeof buf, stdin) == NULL) {
    puts("EOF");
  } else {
    int n = 0;
    sscanf(buf," %*1[+-]%*1[ ]%*[0-9] %n", &n);
    if (n == 0) {
      puts("Fail - conversion incomplete");
    } else if (buf[n] != '\0') {
      puts("Fail - Extra garbage");
    } else {
      char sign;
      int number;
      sscanf(buf," %c%d", &sign, &number);
      printf("Success %c %d\n",sign, number);
    }
  }

"%n" Saves the count of characters scanned.

Tip: Appending %n" to int n = 0; ... sscanf(..., "... %n" to the end of a format is an easy trick to 1) test if scanning was incomplete if (n == 0) and 2) test for trailing non-white-space if (buf[n] != '\0')

Note: No checks for overflow.



回答2:

You seem to have forgotten a comma here:

scanf(" %c %d", &sign &number)

Also the space is both redundant and erroneous. It should be

scanf(" %c%d", &sign, &number)


标签: c scanf