I am attempting to format a space-delimited user input for a programming assignment.
Essentially, the input consists of an arbitrary number of expressions
L integer integer integer integer
and C integer integer integer
.
For example: L 1 1 5 7 C 4 5 3
.
So far, I've managed to extract the integers depending on the initial character, and can iterate through the string using the scanf function:
char a;
while(scanf("%c", &a) == 1){
if(a == 'C'){
int inputX, inputY, inputR;
scanf("%d %d %d", &inputX, &inputY, &inputR);
printf("%d %d %d\n", inputX, inputY, inputR);
}
else if(a == 'L'){
int x1, y1, x2, y2;
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
printf("%d %d %d %d\n", x1, y1, x2, y2);
}
}
Unfortunately, although this outputs the desired integers, the loop (and user input prompt) doesn't terminate.
Could someone please enlighten me as to why this is happening?
This is because
\n
is always there to makescanf("%c", &a) == 1
always true.Change your
to
A space before
%c
will eat up this\n
left behind byscanf
(on pressing Enter).Combining some features of other posts and some additions.
Use
fgets()
and%n
insidesscanf()
. Be sure to check results ofsscanf()
.The reason is scanf reads directly from the standard input and which blocks and waits for user input after it has processed the line. What you need to do is read the line and process that line in your while loop. I've modified your code below.