1

I have a file and I need to check if its lines are in the following format:

name: name1,name2,name3,name4 ...

(some string, followed by ":", then a single space and after that strings separated by ",").

I tried doing it with the following code:

int result =0;

do
{
    result =sscanf(rest,"%[^:]: %s%s", p1,p2,p3);
    if(result==3)
    {
        printf("invalid!");
        fclose(fpointer);
        return -1;
    }
}while (fgets(rest ,LINE , fpointer) != NULL);

this works good for lines like: name: name1, name2 (with space between name1, and name2).

but it fails with the following line:

name : name1,name2

I want to somehow tell sscanf not to avoid this white space before the ":".

could someone see how ?

Thanks for helping!

infinity
  • 158
  • 2
  • 10
  • Probably `%[^,]` helps (preceded by a blank to skip optional white space), looking for a sequence of non-commas. You'll also need to be able to repeat your scan if you need to handle 3, 4, 5, … names. For that, see [How to use `sscanf()` in loops?](http://stackoverflow.com/questions/3975236/) – Jonathan Leffler Aug 12 '16 at 08:21
  • So, what is your actual requirement, then? *(some string, followed by ":", then a single space and after that strings separated by ",")* - perhaps you should rewrite this to include "one or more spaces" between each of these separators. – vgru Aug 12 '16 at 08:21
  • The [`scanf`](http://en.cppreference.com/w/c/io/fscanf) family of functions are not really good candidates for general parsing. Instead you might want to search for the colon `':'` using [some other function](http://en.cppreference.com/w/c/string/byte/strchr) and then use `sscanf` to extract the other two strings. – Some programmer dude Aug 12 '16 at 08:24
  • Suggestion, you can use strtok() for parsing. – Rafal Aug 12 '16 at 08:57

1 Answers1

1

This works for me:

result = sscanf(rest,"%[^*:]: %[^,],%s", p1, p2, p3);

Notice the * is used to consume the space (if any).

David Ranieri
  • 39,972
  • 7
  • 52
  • 94