Sscanf gets the value of the remaining string

I have a line that looks like this:

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

I am trying to get HELLO, 200 and the remaining line. Unfortunately, the string may contain \n and \t , 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); 

after that the variables are:

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

Is there any way to do this without strtok?

+6
source share
2 answers

You can use scanset for the entire range of type unsigned char :

 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 a space after the number, the third qualifier will not match anything, and sscanf will return 2 , leaving the response unchanged.

+6
source

The specifier% n will display the number of characters used in the scan. This should get the number of characters used when scanning the first values, and then strcpy from this index.

 int used; sscanf (str, "%s %d %n", message, &status, &used); strcpy ( response, &str[used]); 
+6
source

All Articles