Converting string to number and number to string using C language

CServer Side ProgrammingProgramming

Problem

What do you mean by String to number and number to string conversion in C programming language?

Solution

There are two functions available for conversion. They are −

  • sscanf() − convert string to number
  • sprintf () − used for converting number to string

String to number conversion

We can convert string to number using the sscanf() function −

Syntax

sscanf (string name, “control string”,variable list)

Example

#include<stdio.h>
main (){
   char a[20] = “02 01 2010”;
   int day, mon, yr;
   clrscr();
   sscanf (a, “%d%d %d”, &day, &mon, &yr);
   printf ( “Day =%d”, day);
   printf ( “Month = %d”, mon);
   printf ( “Year = %d”, yr);
   getch ();
}

Output

Day = 02
Month = 01
Year = 2010

Number to string conversion

We can convert string to number using the sprintf() function −

Syntax

sprintf ( string name, “control string”, variable list)

Example

#include<stdio.h>
main (){
   char a[50];
   int day,mon,yr;
   day = 02;
   mon = 01;
   yr = 2010;
   crlscr();
   sprintf (a, “%d/%d/%d”, day, mon, yr);
   printf ( “today’s date =%s”,a);
   getch ();
}

Output

Today’s date is 02/01/2010.
raja
Published on 08-Mar-2021 14:19:28
Advertisements