scanf() only sign and number

后端 未结 2 1459
野趣味
野趣味 2021-01-19 04:41

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

 input:
 + 10
 output:
 OK, \"sign = +\" and \"numb         


        
相关标签:
2条回答
  • 2021-01-19 05:18

    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.

    0 讨论(0)
  • 2021-01-19 05:28

    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)
    
    0 讨论(0)
提交回复
热议问题