Home > Backend Development > C++ > body text

Convert string to number and number to string using C language

WBOY
Release: 2023-08-29 11:49:04
forward
1023 people have browsed it

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)
Copy after login

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 ();
}
Copy after login

Output

Day = 02
Month = 01
Year = 2010
Copy after login

Convert number to string

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

Syntax

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

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 ();
}
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template