Reputation: 4358
scanf("%s %d %s %d",word1,&num1,word2,&num2);
so when the user inputs "quit", its supposed to stop asking for the other 3 inputs. however it asks me to input another "quit" probably because there are 2 %s in the format
is there anyway around this? EDIT: because it has to get 4 inputs in a loop, unless a quit is inputted.
Upvotes: 1
Views: 3730
Reputation: 488103
scanf
is a very blunt tool that is not good at talking to unstructured inputs (including humans :-) ). In general, if you are interacting with a person, you should start with fgets
to read a line, then pick the resulting line apart however is most convenient, possibly including sscanf
.
It's worse than you think because the %d
directive will jam up if you feed it something that is not scan-able as an integer. For instance, if you enter quit now
, the first %s
directive will read the word quit
but the %d
will leave now
in the input stream, causing scanf
to return 1 (one successful conversion-and-assignment). The next attempt to read a string will obtain and consume the now
; to naive code, this will seem like it was a later, second input line, rather than a continuation of the first one.
Upvotes: 3
Reputation: 23058
#include <stdio.h>
#include <string.h>
scanf("%s ", word1);
if (strcmp(word1, "quit") != 0)
scanf("%d %s %d", &num1, word2, &num2);
Upvotes: 2