sscanf
- C course
- Beginner
- Lesson 92/116
- 5 min
Learn to read values from a string with sscanf.
sscanf: formatted reading from a string
The sscanf function works like scanf but reads from a string instead of the keyboard. It comes with the <stdio.h> header. Its signature is int sscanf(const char *s, const char *fmt, ...).
char input[] = "Ali 25";
char name[16];
int age;
int n = sscanf(input, "%s %d", name, &age);
// n = 2, name = "Ali", age = 25The return value is the number of fields successfully read. Because name is a string, it is passed directly; age is an int so its address is passed as &age. This is a powerful tool to parse structured text.
Parsing name and age with sscanf
sscanf can extract multiple values from a string. The format string describes how each part is read.
char input[] = "Ayse 30";
char name[16];
int age;
sscanf(input, "%s %d", name, &age);
printf("%s %d\n", name, age);
// "Ayse 30"Here %s reads up to the next space into name, and %d reads the number into age. The &age address operator gives the location of age in memory so that sscanf can write its value there. A string is passed by name because the name itself is already an address.
Practice Parse name and age
Use sscanf to read a name string and an age integer from "Alex 25". Then print n, name and age with printf using the "%d %s %d\n" format.
Starter code
#include <stdio.h>
int main(void) {
char input[] = "Alex 25";
/* Define name and age; read with sscanf; print with printf */
return 0;
}Sample solution
char name[16];
int age;
int n = sscanf(input, "%s %d", name, &age);
printf("%d %s %d\n", n, name, age);Expected output
2 Alex 25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the sscanf call return?
- The number of matched fields Correct answer
- The number of characters written
- An error code
- A pointer
Explanation: sscanf returns the number of fields successfully read.
2 Match function to source
| Term | Meaning |
|---|---|
sscanf |
Reads from a string |
scanf |
Reads from the keyboard |
%s %d |
Reads two fields |
return |
Match count |
3 Fill in the blank: sscanf call
int n = ____(input, "%s %d", name, &age);
int n = sscanf(input, "%s %d", name, &age);
Explanation: sscanf reads from a string.