Search code examples
cscanf

C ignore dashes on scanf


I'm trying to load in two values from a string separated by " - ".
I can't figure out what to put in the scanf to ignore this dash.

Here's a simplified snippet that illustrates the problem:

char first[3];
char second[3];

char* str = "foo - bar";
sscanf(str, "%s <what should be here> %s", first, second);

printf("%s %s", first, second);

If nothing is placed in the placeholder the program prints "foo -"


Solution

  • To tell scanf to expect a -, put a - in the format string:

    sscanf(str, "%s - %s", first, second);
    

    Also, make your arrays big enough to hold the characters you expect plus a terminating null character:

    char first[4];
    char second[4];
    

    You should also limit scanf to the size of the receiving arrays:

    sscanf(str, "%3s - %3s", first, second);
    

    If the - might not be present, you need additional code to handle that; a simple scanf is insufficient. Similarly, if the strings might be longer than three characters, you need additional code.