The sscanf () function is used to read data from a string in the specified format, which is prototyped as follows:
int sscanf (char *str, char * format [, argument, ...]);
The parameter parameter str is a string to read data from, format is the user-specified form, and argument is a variable that holds the data read.
"Return value" succeeds returns the number of arguments, failure returns 1, and the reason for the error is stored in errno.
SSCANF () Converts the string of the parameter str according to the parameter format (formatted string) and formats the data (formatted string refer to scanf ()), and the converted result is stored in the corresponding variable.
SSCANF (), similar to scanf (), is used for input, except that scanf () takes the keyboard (stdin) as the input source, and sscanf () takes a fixed string as the input source.
"instance" reads integers and lowercase letters from the specified string.
#include <stdio.h>int main (void) { char str[100] = "123568qwerSDDAE"; Char lowercase[100]; int num; SSCANF (str, "%d%[a-z]", &num, lowercase); printf ("The number is:%d.\n", num); printf ("The lowercase is:%s.", lowercase); return 0;}
You can see that the format parameter is similar to a regular expression (of course, there is no strong regular expression, and complex strings are recommended for regular expression processing), which supports collection operations such as:
%[a-z] to match any character in a to Z, greed (as many matches as possible)
%[ab ' matches a, B, ' one member, greed
%[^a] matches any character not a, greed
In addition, format can not only delimit strings with spaces, but can also be defined with other characters, enabling simple string segmentation (more flexible string splitting using strtok ()). For example:
SSCANF ("2006:03:18", "%d:%d:%d", A, B, c);
SSCANF ("2006:03:18-2006:04:18", "%s-%s", sztime1, sztime2);
int32_t getsecsbyhourtime (const char* STR)
{
if (NULL = = str)
{
return 0;
}
int32_t nhour = 0;
int32_t nmins = 0;
int32_t nsecs = 0;
SSCANF (str, "%d:%d:%d", &nhour,&nmins,&nsecs);
Return nhour*second_per_hour + Nmins*second_per_minute + nsecs;
}
C language sscanf () function