Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

c - Scanf takes two values in loop for standard input but needs to take only one to end loop

So one of the requirements for this code is that it takes the scan of the score and name from the same line so I have them in the same scanf and that entering q will break the loop and stop the input. The issue is that when entering Q without a number it will take another input before stopping the loop. Are there any fixes I can do to make this work?

     while(entered_name[0] != 'Q' && entered_name[1] != 0)
     {
        
        scanf(" %s %d", entered_name, &new_score);
        if(entered_name[0] == 'q')
        {
            entered_name[0] = toupper(entered_name[0]);
        }
     }
question from:https://stackoverflow.com/questions/66052800/scanf-takes-two-values-in-loop-for-standard-input-but-needs-to-take-only-one-to

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should consume the input line with fgets() because scanf() can get stuck as soon as the actual input does not match what is expected in the format string.

Then in a second time, you can analyse the obtained line with sscanf().

The result gives the number of % that were successfully extracted (starting from the left), thus you can distinguish the cases where one or two information were given on this line.

/**
  gcc -std=c99 -o prog_c prog_c.c 
      -pedantic -Wall -Wextra -Wconversion 
      -Wc++-compat -Wwrite-strings -Wold-style-definition -Wvla 
      -g -O0 -UNDEBUG -fsanitize=address,undefined
**/

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

int
main(void)
{
  char entered_name[100]="";
  int new_score=-1;
  while((strcmp(entered_name, "Q")!=0)&&
        (strcmp(entered_name, "q")!=0))
  {
    char line[100];
    if(fgets(line, sizeof(line), stdin)==NULL)
    {
      break; // cannot read standard input any more
    }
    int r=sscanf(line, "%s %d", entered_name, &new_score);
    switch(r) // number of % extracted
    {
      case 1:
      {
        printf("entered name only: %s
", entered_name);
        break;
      }
      case 2:
      {
        printf("entered name and score: %s %d
", entered_name, new_score);
        break;
      }
      default:
      {
        printf("sorry, I didn't understand.
");
      }
    }
  }
  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...