Reputation: 25392
I have a while loop with scanf()
that reads in a single char* value:
char c[9];
while(c != 'q')
{
scanf("%s", c);
}
c
is then compared with multiple one-character strings to determine which operation should be performed.
This scanf can receive multiple arguments and I need to know when only one argument is provided to the function or if there are multiple arguments, but whenever I type in more than one argument, the while loop is run separately for each argument entered.
So say I enter something like "a b c d", the while loop will process c="a"
, c="b"
, c="c"
, and c="d"
, which is fine, but I need to know that I entered 4 non-white-space elements in the last scan.
So the first argument is the command I am going to run which is a letter, followed by between 0 and 3 arguments for that command, which are strings or numbers:
Example:
"a box 1 2"
When the number of arguments are fixed, I just used a boolean value to know that the next x values of c are supposed to be the arguments, but I have one function which can accept 0 or 1 arguments, e.g.
"b" is acceptable.
"b 25" is acceptable.
b
is basically a search function where the optional argument is the query to check against. If no argument is provided, it lists all items. So a boolean value won't work in this case because the number of arguments is not fixed.
So I need to know that if I enter:
"a 1 2 3" x=4
"a 1" x=2
"a" x=1
Upvotes: 1
Views: 2223
Reputation: 154305
Separate IO from scanning/parsing.
char buf[100];
fgets(buf, sizeof buf, stdin);
int count = 0; // Count of arguments.
char *p = buf;
while (*p) {
if (!isspace((unsigned char) *p)) {
count++;
// Do something, if desired with *p
}
else {
Handle_UnexpectedWhiteSpaceChar();
}
if (isspace((unsigned char) *p)) {
p++;
}
else {
Handle_UnexpectedTwoNonSpaceChar();
}
Upvotes: 1
Reputation: 781716
This will allow you to type a series of numbers on each line, until you enter q
.
char line[1024] = "";
int nums[MAXNUMS];
int counter = 0;
while (strcmp(line, "q\n") != 0) {
fgets(line, sizeof(line), stdin);
while (counter < MAXNUMS && sscanf("%d", &nums[counter])) {
counter++;
}
}
Upvotes: 0