To contents Next section

7.1 sscanf

Sscanf may look exactly like a normal function, but normal functions can not set the variables you send to it. The purpose of sscanf is to match one string against a format string and place the matching results into a list of variables. The syntax looks like this:
int sscanf(string str, string fmt, lvalue ...)
The string str will be matched against the format string fmt. fmt can contain strings separated by %d,%s,%c and %f. Every % corresponds to one lvalue. An lvalue is the name of a variable, a name of a local variable, an index in an array, mapping or object. It is because of these lvalues that sscanf can not be implemented as a normal function.

Whenever a percent is found in the format string, a match is according to the following table:
%b reads a binary integer
%d reads a decimal integer
%o reads an octal integer
%x reads a hexadecimal integer
%D reads an integer that is either octal (leading zero), hexadecimal (leading 0x) or decimal.
%f reads a float
%c matches one char and returns it as an integer
%2c matches two chars and returns them as an integer (short)
%4F matches four chars and returns them as a float (IEEE single precision)
%8F matches eigth chars and returns them as a float (IEEE double precision)
%s reads a string. If followed by %d, %s will read any non-numerical characters. If followed by a %[], %s will read any characters not present in the set. If followed by normal text, %s will match all characters up to but not including the first occurrence of that text.
%5s gives a string of 5 characters (5 can be any number)
%[set] matches a string containing a given set of characters (those given inside the brackets). %[^set] means any character except those inside brackets. Example: %[0-9H] means any number or 'H'.
%{format%} Repeatedly matches 'format' as many times as possible and assigns an array of arrays with the results to the lvalue.

If a * is put between the percent and the operator, the operator will only match its argument, not assign any variables.

Sscanf does not use backtracking. Sscanf simply looks at the format string up to the next % and tries to match that with the string. It then proceeds to look at the next part. If a part does not match, sscanf immediately returns how many % were matched. If this happens, the lvalues for % that were not matched will not be changed.

Let's look at a couple of examples:

// a will be assigned "oo" and 1 will be returned
sscanf("foo","f%s",a);

// a will be 4711 and b will be "bar", 2 will be returned
sscanf("4711bar","%d%s",a,b);

// a will become "test"
sscanf(" \t test","%*[ \t]%s",a)

// Remove "the " from the beginning of a string
// If 'str' does not begin with "the " it will not be changed
sscanf(str,"the %s",str);

SEE ALSO : sprintf


To contents Next section