Understanding how sscanf works
sscanf() is a function used to convert a string to one or more variables. To see the documentation for sscanf you can use the man pages that are built into Linux.
man sscanf
The signature of the function is as follows:
int sscanf(const char *str, const char *format, ...);
This function takes a variable number of arguments, shown by the … at the end of the function. This is not the first function we have seen that takes a variable number of arguments. The printf function also takes a variable number of arguments.
The first two arguments to sscanf are strings (pointers to a char array). The first string is the input that you want to convert. For example, you may have an input string which is several numbers (represented as a string), that you would like to convert to integers.
The second argument (also a string) is a format specifier. This is a description of what in the input string you want converted, and to what type. It is specified as conversion specifiers (which start with the % symbol). The remaining arguments are pointers which hold the value of any conversions from the string.
The function returns an int, which is the number of variables that were converted from the input string. Let’s see an example of sscanf in action.
// Example to show how sscanf works. Used in the introducing the bomblab.
//
// To compile:
// gcc -Wall -Og -o sscanf sscanf.c
void main(void) {
// String of numbers
char *str = "14 20 30";
// ints to hold those numbers
int x, y, z;
int numConverted = 0;
// convert the string to the numbers
numConverted = sscanf(str, "%d %d %d", &x, &y, &z);
if (numConverted == 3) {
printf("Your numbers are: %d, %d, and %d.\n", x, y, z);
}
else {
printf("Could not convert string to integers\n");
}
}
Let’s go over this code. We first declare the string of numbers we want to convert (str). This could be an input string from the user. Next we declare the three variables (x, y, and z) that will hold the integers we will convert. Lastly, we declare numConverted which will hold the return value from sscanf.
Let’s take a look at the scanf line.
numConverted = sscanf(str, "%d %d %d", &x, &y, &z);
The first argument to sscanf is the input string (which will be converted). The next argument is the format specifier string for the conversion. The %d means to scan the input string and match on an integer (this is the same specifier you use in a printf statement to print out an integer value). We have three %d format specifiers in this string, so we will try to convert three integers and store them in the variables x, y, and z. Note that sscanf takes a pointers as arguments for the variables that hold the conversion. This is why we pass in the address of x, y, and z (as &x, &y, and &z).
Download and try running the code to make sure you understand how it works.