Scanf () only sign and number

I want to get the variable sign and number using scanf ().
How it should work:

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

 

 input:
 +10
 output:
 Fail!

 

 input:
 10
 output:
 Fail!

 

 input:
 a
 output:
 Fail!

I tried this solution, but it did not work for me. Especially for inputs: +10 and

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

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

Thanks.

+4
source share
2 answers

scanf(" %c %d", &sign &number) != 2does not work because the format does not require a space between charand int. A " "matches 0 or more spaces, not one ' '.


Thus, the code should look for the 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 space.
"%d"Scan the white spaces, then int.


. fgets(), , sscanf().


[] - fgets(), 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" .

: %n" int n = 0; ... sscanf(..., "... %n" - : 1) , if (n == 0) 2) if (buf[n] != '\0')

. .

+5

, , :

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

.

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

Source: https://habr.com/ru/post/1615481/


All Articles