Home »
Code Snippets »
C/C++ Code Snippets
C program to get integer (number) from string using sscanf.
By: IncludeHelp, On 02 NOV 2016
Here we will learn how we can extract an integer number from a given string using sscanf() library function?
What is sscanf() in c programming?
sscanf is used to read formatted data from a string, here we can get any kind of value by specifying its type (through format specifier) from a string.
Syntax
int sscanf ( const char * s, const char * format, ...);
Reference: http://www.cplusplus.com/reference/cstdio/sscanf/
In this example we are reading a string (character array) though keyboard and will extract integer value; then store the value in an integer variable.
#include <stdio.h>
int main()
{
char text[10]; /*input text*/
int age; /*to store extracted int value*/
printf("Enter your age: ");
fgets(text,sizeof(text),stdin);
/*Extracting int value...*/
sscanf(text,"%d",&age);
printf("Entered age is: %d\n",age);
return 0;
}
Output
Enter your age: 23
Entered age is: 23