Reputation: 31503
I'm trying to parse a line like
1 {2} {2,3} {4}
into 4 different character arrays
where 1 is '1','\0'
and the other numbers in brackets are each '2'
'2','3'
'4'
I've tried strtok with dilems " \t}" and I've also tried sscanf passing it %s for the first column and "{%S}" for the remaining columns. Neither are giving me expected results. Can anyone give me a push in the right direction?
Upvotes: 0
Views: 131
Reputation: 264551
Your problem is that %S
parses a space terminated word (so it reads the '}' as part of the string.
fscanf(stream, "{%[^}]}", buffer);
Will scan the characters between '{}' into a buffer.
Note: you may also want to be careful about buffer overflow here.
"{%[^}]}"
{ -> Matches {
%[<char>] -> Matches a sequence of characters that match any of the characters in <char>
If the first character is ^ this makes it a negative so any characters that
do not follow the ^
%[^}] -> Matches a sequence of characters that does not match `}`
} -> Matches }
But I would try and parse the numbers out individually.
// If the input does not contain '{' next then we get an error and the
// next section of code is not entered.
if (fscanf(stream, " {") != EOF)
// Note: The leading space matches one or more white space characters
// So it is needed to get passed leading white space.
{
// We enter this section only if we found '{'
int value;
char next;
while(fscanf(stream, "%d%c", &value, &next) == 2)
{
// You have an integer in value
if (next == '}')
{ break;
}
if (next == ',')
{ continue;
}
// You have an error state the next character after the number was not
// a space or a comma ',' or end of section '}'
}
}
With this code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
while (scanf(" {") != EOF)
{
printf("Enter BLOCK\n");
int value;
char next;
while(scanf("%d%c", &value, &next) == 2)
{
if ((next == '}') || (next == ','))
{
printf("\tVALUE %d\n",value);
}
if (next == '}')
{ break;
}
if (next == ',')
{ continue;
}
printf("ERROR\n");
exit(1);
}
printf("EXIT BLOCK\n");
}
}
Then use like this:
> gcc gh.c
> echo " {2} {2,3} {4}" | ./a.out
Enter BLOCK
VALUE 2
EXIT BLOCK
Enter BLOCK
VALUE 2
VALUE 3
EXIT BLOCK
Enter BLOCK
VALUE 4
EXIT BLOCK
Upvotes: 1