Home > Backend Development > C++ > C program to convert a number to string

C program to convert a number to string

PHPz
Release: 2023-08-25 18:17:13
forward
1322 people have browsed it

C program to convert a number to string

In this section, we will learn how to convert a number (integer or floating point or any other numeric type data) into a string.

The logic is very simple. Here we will use sprintf() function. This function is used to print certain values ​​or lines into a string but not in the console. This is the only difference between printf() and sprintf(). The first parameter here is the string buffer. Where we want to save the data.

Input: User will put some numeric value say 42.26
Output: This program will return the string equivalent result of that number like "42.26"
Copy after login

Algorithm

Step 1: Take a number from the user
Step 2: Create an empty string buffer to store result
Step 3: Use sprintf() to convert number to string
Step 4: End
Copy after login

Sample code

Real-time demonstration

#include<stdio.h>
main() {
   char str[20];    //create an empty string to store number
   float number;
   printf("Enter a number: ");
   scanf("%f", &number);
   sprintf(str, "%f", number);   //make the number into string using sprintf function
   printf("</p><p>You have entered: %s", str);
}
Copy after login

Output:

Enter a number: 46.3258
You have entered: 46.325802
Copy after login

The above is the detailed content of C program to convert a number to string. 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