In this source code example, we will see how to use the sscanf() function in C programming with an example.
Function Overview
sscanf() is like the twin of sprintf(). But instead of creating strings, sscanf() reads data from a string. Think of it as the reverse of sprintf(). It is in the C library <stdio.h>.
Source Code Example
#include <stdio.h>
int main() {
char info[] = "Ram 25 painter";
char name[10];
int age;
char job[20];
// Reading data from a string into different variables
sscanf(info, "%s %d %s", name, &age, job);
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Job: %s\n", job);
char moreInfo[] = "10.5 2023";
double salary;
int year;
// Reading a double and an int from another string
sscanf(moreInfo, "%lf %d", &salary, &year);
printf("Salary: %.1lf thousand\n", salary);
printf("Year: %d\n", year);
return 0;
}
Output
Name: Ram Age: 25 Job: painter Salary: 10.5 thousand Year: 2023
Explanation
Look at the code, and you'll see:
1. We used sscanf() to get Ram's name, age, and job from a string.
2. We used it again to learn about his salary and the year from a different string.
In short, sscanf() is super useful when you want to take apart a string and find out what's inside!
Comments
Post a Comment