ADVERTISEMENT
ADVERTISEMENT

Home » Code Snippets » C/C++ Code Snippets

C program to get integer (number) from string using sscanf.

By: IncludeHelp, On 02 NOV 2016

ADVERTISEMENT

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

COMMENTS

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.