Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

Is there a way to do it without strtok?

like image 934
plainerman Avatar asked Jan 30 '16 12:01

plainerman


People also ask

What value does sscanf return?

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.

What does %n do in sscanf?

When we use the %n specifier in scanf() it will assign the number of characters read by the scanf() function until it occurs.

What is the difference between scanf and sscanf?

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.

Does sscanf ignore whitespace?

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 .


2 Answers

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.

like image 104
chqrlie Avatar answered Oct 05 '22 18:10

chqrlie


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]);
like image 32
user3121023 Avatar answered Oct 05 '22 19:10

user3121023