main(){ chara"/> main(){ chara">

Home >Backend Development >C++ >Convert string to number and number to string using C language

Convert string to number and number to string using C language

WBOY
WBOYforward
2023-08-29 11:49:041042browse

Question

What does string to number and number to string conversion mean in C programming language?

Solution

There are two functions available for conversion. They are -

  • sscanf() - Converts string to number
  • sprintf () - Used to convert number to string

characters String to number conversion

We can use the sscanf() function to convert a string to a number-

Syntax

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

Convert string to number and number to string using C language

Example

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

Output

Day = 02
Month = 01
Year = 2010

Convert number to string

We can use sprintf() function to convert string to number −

Syntax

sprintf ( string name, &ldquo;control string&rdquo;, variable list)

Convert string to number and number to string using C language

Example

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

Output

Today&rsquo;s date is 02/01/2010.

The above is the detailed content of Convert string to number and number to string using C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete