Search code examples
carraysstringcharscanf

sscanf get the value of the remaining string


I have a String which looks like this:

"HELLO 200 Now some random text\n now more text\t\t"

I try to get the HELLO, the 200, and the remaining string. Unfortunately the string may contain \n's and \t's so i cannot use %[^\n\t].

I tried the following approach:

char message[MESSAGE_SIZE], response[RESPONSE_SIZE];
int status;
sscanf (str, "%s %d %[^\0]", message, &status, response);

afterwards the variables are

message = "HELLO", status = 200, response = "HELLO 200 Now some random text\n now more text\t\t"

but this includes HELLO 200 in the response string (which should not be there). Is there a way to achieve this with scanf directly, without strtok?


Solution

  • You could use scanset for the whole range of the unsigned char type:

    char message[MESSAGE_SIZE], response[RESPONSE_SIZE];
    int status;
    *response = '\0';
    sscanf(str, "%s %d %[\001-\377]", message, &status, response);
    

    Plus you should always check the return value from sscanf. If there is only white space after the number, the third specifier will not match anything and sscanf will return 2, leaving response unchanged.