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"
Is there a way to do it without strtok?
The sscanf() function returns the number of fields that were successfully converted and assigned. The return value does not include fields that were read but not assigned. The return value is EOF when the end of the string is encountered before anything is converted.
When we use the %n specifier in scanf() it will assign the number of characters read by the scanf() function until it occurs.
The scanf function reads data from standard input stream stdin into the locations given by each entry in the argument list. The argument list, if it exists, follows the format string. The sscanf function reads data from buffer into the locations given by argument list.
Template strings for sscanf and related functions are somewhat more free-form than those for printf . For example, most conversion specifiers ignore any preceding whitespace. Further, you cannot specify a precision for sscanf conversion specifiers, as you can for those of printf .
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.
The %n specifier will capture the number of characters used in a scan. This should get the number of characters used in scanning the first values then strcpy from that index.
int used;
sscanf (str, "%s %d %n", message, &status, &used);
strcpy ( response, &str[used]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With