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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…