The Wayback Machine - https://web.archive.org/web/20240822220240/https://www.geeksforgeeks.org/converting-number-to-string-in-cpp/
Open In App

Converting Number to String in C++

Last Updated : 18 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, converting integers to strings or converting numbers to strings or vice-versa is actually a big paradigm shift in itself. In general or more specifically in competitive programming there are many instances where we need to convert a number to a string or string to a number. Let’s look at some methods to convert an integer or a number to a string.

Converting Number to String in C++

There are 4 major methods to convert a number to a string, which are as follows:

  • Using to_string()
  • Using string Stream
  • Using sprintf() function
  • Using boost lexical cast

Method 1: Using to_string()

The to_string() function can be used to convert an integer, floating point values, or any number to a string. This function accepts a number(which can be any data type) and returns the number as the desired string.

Syntax:

string to_string (int val);

Parameters:

  • val – Any Numerical Value.

Return Value:

  • A string object containing the representation of value as a sequence of characters.

Example:

C++




// C++ code to demonstrate "to_string()" method
// to convert number to string.
#include <iostream>
#include <string> // for string and to_string()
using namespace std;
 
// Driver Code
int main()
{
    // Declaring integer
    int i_val = 20;
 
    // Declaring float
    float f_val = 30.50;
 
    // Conversion of int into string using
    // to_string()
    string stri = to_string(i_val);
 
    // Conversion of float into string using
    // to_string()
    string strf = to_string(f_val);
 
    // Displaying the converted strings
    cout << "The integer in string is : ";
    cout << stri << endl;
    cout << "The float in string is : ";
    cout << strf << endl;
 
    return 0;
}


Output

The integer in string is : 20
The float in string is : 30.500000

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 2: Using string streams

In this method, a string stream declares a stream object which first inserts a number, as a stream into an object and then uses “str()” to follow the internal conversion of a number to a string.

Example:

C++




// C++ code to demonstrate string stream method
// to convert number to string.
#include<iostream>
#include <sstream>  // for string streams
#include <string>  // for string
using namespace std;
int main()
{
    int num = 2016;
 
    // declaring output string stream
    ostringstream str1;
 
    // Sending a number as a stream into output
    // string
    str1 << num;
 
    // the str() converts number into string
    string geek = str1.str();
 
    // Displaying the string
    cout << "The newly formed string from number is : ";
    cout << geek << endl;
 
    return 0;
}


Output

The newly formed string from number is : 2016

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 3: Using the sprintf() function

sprintf() function stores the output on the char buffer specified in the function, instead of printing the output on the console.

C++




// C++ Program to illustrate the use of sprintf() for number
// to string conversion
#include <iostream>
using namespace std;
 
int main()
{
    // any num
    int n = 12234;
    // string buffer
    char str[1000];
 
    // sprintf() to print num to str buffer
    sprintf(str, "%d", n);
 
    cout << "the string is : " << str;
 
    return 0;
}
 
// this code is contributed by shivanisingh


Output

the string is : 12234

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 4: Using boost lexical cast

Similar to string conversion, the ” lexical_cast() ” function remains the same, but in the ‘boost lexical cast‘ time argument list modifies to “lexical_cast(numeric_var).  

Example:

C++




// C++ code to demonstrate "lexical_cast()" method
// to convert number to string.
#include <boost/lexical_cast.hpp> // for lexical_cast()
#include <iostream>
#include <string> // for string
using namespace std;
 
// Driver Code
int main()
{
    // Declaring float
    float f_val = 10.5;
 
    // Declaring int
    int i_val = 17;
 
    // lexical_cast() converts a float into string
    string strf = boost::lexical_cast<string>(f_val);
 
    // lexical_cast() converts a int into string
    string stri = boost::lexical_cast<string>(i_val);
 
    // Displaying string converted numbers
    cout << "The float value in string is : ";
    cout << strf << endl;
    cout << "The int value in string is : ";
    cout << stri << endl;
 
    return 0;
}


Output

The float value in string is : 10.5
The int value in string is : 17

Time Complexity: O(n)
Auxiliary Space: O(n)

 



Similar Reads

Converting String into Set in C++ STL
Prerequisites: String in C++Set STL in C++ A string is a collection of characters and if we are converting it into a set the only reason can be to check the characters being used without duplicate values. Example: string s="Geeks for Geeks is for Geeks" // G e k s f o r i are characters // set can store these characters in sorted order. So, to Perf
2 min read
std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++ String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let's see a few of the functionalities string class provides. Header File &lt;string&gt; String Functionalities The
6 min read
std::string::remove_copy(), std::string::remove_copy_if() in C++
remove_copy() It is an STL function in c++ which is defined in algorithm library. It copies the elements in the range [first, last) to the range beginning at result, except those elements that compare equal to given elements. The resulting range is shorter than [first,last) by as many elements as matches in the sequence, which are "removed". The re
4 min read
Check if a string can be formed from another string using given constraints
Given two strings S1 and S2(all characters are in lower-case). The task is to check if S2 can be formed from S1 using given constraints: 1. Characters of S2 is there in S1 if there are two 'a' in S2, then S1 should have two 'a' also. 2. If any character of S2 is not present in S1, check if the previous two ASCII characters are there in S1. e.g., if
7 min read
Print all possible combinations of the string by replacing '$' with any other digit from the string
Given a number as a string where some of the digits are replaced by a '$', the task is to generate all possible number by replacing the '$' with any of the digits from the given string.Examples: Input: str = "23$$" Output: 2322 2323 2332 2333Input: str = "$45" Output: 445 545 Approach: Find all the combinations of the string by replacing the charac
15+ min read
Periodic Binary String With Minimum Period and a Given Binary String as Subsequence.
Periodic Binary String: A Binary string is called periodic if it can be written as a repetition of a binary string of smaller or same length. For example, 101010 is a periodic binary string with period 10 as we can get the string by repeatedly appending 10 to itself. In general, the string S with period P means, Si is equal to Si + P. Problem: Give
5 min read
Lexicographically smallest string which is not a subsequence of given string
Given a string S, the task is to find the string which is lexicographically smallest and not a subsequence of the given string S. Examples: Input: S = "abcdefghijklmnopqrstuvwxyz"Output: aaExplanation:String "aa" is the lexicographically smallest string which is not present in the given string as a subsequence. Input: S = "aaaa"Output: aaabExplanat
5 min read
Minimum subsequences of a string A required to be appended to obtain the string B
Given two strings A and B, the task is to count the minimum number of operations required to construct the string B by following operations: Select a subsequence of the string A.Append the subsequence at the newly formed string (initially empty). Print the minimum count of operations required. If it is impossible to make the new string equal to B b
8 min read
Check if given string is a substring of string formed by repeated concatenation of z to a
Given a string str, the task is to check if string str is a substring of an infinite length string S in which lowercase alphabets are concatenated in reverse order as: S = "zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba...." Examples: Input: str = "cbaz"Output: YES Explanation:Given string "cbaz" is a valid sub string of S. Input: str = "ywxt
10 min read
How to find length of a string without string.h and loop in C?
Find the length of a string without using any loops and string.h in C. Your program is supposed to behave in following way: Enter a string: GeeksforGeeks (Say user enters GeeksforGeeks) Entered string is: GeeksforGeeks Length is: 13 You may assume that the length of entered string is always less than 100.The following is the solution. C/C++ Code #i
2 min read
Print substring of a given string without using any string function and loop in C
Write a function mysubstr() in C that doesn't use any string function, doesn't use any loop, and prints substring of a string. The function should not modify contents of string and should not use a temporary char array or string. For example mysubstr("geeksforgeeks", 1, 3) should print "eek" i.e., the substring between indexes 1 and 3. One solution
2 min read
std::string::replace_copy(), std::string::replace_copy_if in C++
replace_copy replace_copy() is a combination of copy() and replace(). It copies the elements in the range [first, last) to the range beginning at result, replacing the appearances of old_value by new_value.The range copied is [first, last), which contains all the elements between first and last, including the element pointed by first but not the el
4 min read
std::string::append vs std::string::push_back() vs Operator += in C++
To append characters, you can use operator +=, append(), and push_back(). All of them helps to append character but with a little difference in implementation and application. Operator += : appends single-argument values. Time complexity : O(n)append() : lets you specify the appended value by using multiple arguments. Time complexity: O(n)push_back
6 min read
Print all occurrences of a string as a substring in another string
Given two strings, str1 and str2, the task is to print the indices(Consider, indices starting from 0) of the occurrence of str2 in str1. If no such index occurs, print "NONE". Examples: Input : GeeksforGeeks GeeksOutput : 0 8Input : GFG gOutput : NONEApproach 1 (Naive Approach): A simple solution is to check all substrings of a given string one by
12 min read
What is the best way in C to convert a number to a string?
Solution: Use sprintf() function. #include&lt;stdio.h&gt; int main() { char result[50]; float num = 23.34; sprintf(result, &quot;%f&quot;, num); printf(&quot;\n The string for the num is %s&quot;, result); getchar(); } You can also write your own function using ASCII values of numbers.
1 min read
C program to count number of vowels and consonants in a String
Given a string and write a C program to count the number of vowels and consonants in this string. Examples: Input: str = "geeks for geeks" Output: Vowels: 5 Consonants: 8 Input: str = "abcdefghijklmnopqrstuvwxyz" Output: Vowels: 5 Consonants: 21Using For LoopsTake the string as inputTake each character from this string to checkIf this character is
4 min read
Kth space-separated number from a given string
Given a string S consisting of space-separated integers, the task is to extract the Kth number present in the string. Note: The string contains at least K numbers in it. Examples: Input: S = "12 13 15", K= 3Output: 15Explanation: The 3rd integer in the above string is 15. Input: S = "10 20 30 40", K = 2Output: 20Explanation: The 2nd integer in the
10 min read
Generate a Number in Decreasing order of Frequencies of characters of a given String
Given a string Str of length N, consisting of lowercase alphabets, the task is to generate a number in decreasing order of the frequency of characters in the given string. If two characters have the same frequency, the character with a smaller ASCII value appears first. Numbers assigned to characters {a, b, ...., y, z} are {1, 2, ...., 25, 26} resp
12 min read
Convert a floating point number to string in C
Write a C function ftoa() that converts a given floating-point number or a double to a string. Use of standard library functions for direct conversion is not allowed. The following is prototype of ftoa(). The article provides insight of conversion of C double to string. ftoa(n, res, afterpoint) n --&gt; Input Number res[] --&gt; Array where output
3 min read
Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters
Given a string S of length N, the task is to make all characters of the string the same by incrementing/decrementing the ASCII value of any character by 1 any number of times. Note: All characters must be changed to a character of the original string. Examples: Input: S = "geeks"Output: 20Explanation:The minimum number of operations can be attained
6 min read
Check if a number is Flavius Number
Given a series of integers from 1 to infinity and a number N.The task is to remove every (i + 1)-th element from the remaining series at every i-th iteration and find whether the given number N exists in the series or not. Flavius Number: Numbers in the Flavius Sieve are called Flavius Numbers.Flavius sieve starts with the natural numbers and keep
5 min read
Check whether a given number is an ugly number or not
Given an integer N, the task is to find out whether the given number is an Ugly number or not . Ugly numbers are numbers whose only prime factors are 2, 3 or 5. Examples: Input: N = 14 Output: No Explanation: 14 is not ugly since it includes another prime factor 7. Input: N = 6 Output: Yes Explanation: 6 is a ugly since it includes 2 and 3. Approac
9 min read
C | String | Question 2
What is the output of following program? # include &lt;stdio.h&gt; int main() { char str1[] = &quot;GeeksQuiz&quot;; char str2[] = {'G', 'e', 'e', 'k', 's', 'Q', 'u', 'i', 'z'}; int n1 = sizeof(str1)/sizeof(str1[0]); int n2 = sizeof(str2)/sizeof(str2[0]); printf(&quot;n1 = %d, n2 = %d&quot;, n1, n2); return 0; } (A) n1 = 10, n2 = 9 (B) n1 = 10, n2
1 min read
C | String | Question 3
What is the output of following program? #include&lt;stdio.h&gt; void swap(char *str1, char *str2) { char *temp = str1; str1 = str2; str2 = temp; } int main() { char *str1 = &quot;Geeks&quot;; char *str2 = &quot;Quiz&quot;; swap(str1, str2); printf(&quot;str1 is %s, str2 is %s&quot;, str1, str2); return 0; } (A) str1 is Quiz, str2 is Geeks (B) str1
1 min read
C | String | Question 4
Predict the output? #include &lt;stdio.h&gt; int fun(char *str1) { char *str2 = str1; while(*++str1); return (str1-str2); } int main() { char *str = &quot;GeeksQuiz&quot;; printf(&quot;%d&quot;, fun(str)); return 0; } (A) 10 (B) 9 (C) 8 (D) Random Number Answer: (B) Explanation: The function fun() basically counts number of characters in input stri
1 min read
C | String | Question 5
What does the following fragment of C-program print? char c[] = &quot;GATE2011&quot;; char *p =c; printf(&quot;%s&quot;, p + p[3] - p[1]) ; (A) GATE2011 (B) E2011 (C) 2011 (D) 011 Answer: (C) Explanation: See comments for explanation. char c[] = "GATE2011"; // p now has the base address string "GATE2011" char *p = c; // p[3] is 'E' and p[1] is 'A'.
1 min read
C | String | Question 6
C/C++ Code #include int main() { char str[] = \"GeeksQuiz\"; printf(\"%s %s %s \", &str[5], &5[str], str+5); printf(\"%c %c %c \", *(str+6), str[6], 6[str]); return 0; } (A) Runtime Error (B) Compiler Error (C) uiz uiz uiz u u u (D) Quiz Quiz Quiz u u u Answer: (D)Explanation: The program has no error. All of the following expressions mean same thi
1 min read
C | String | Question 7
In below program, what would you put in place of “?” to print “Quiz”? C/C++ Code #include int main() { char arr[] = \"GeeksQuiz\"; printf(\"%s\", ?); return 0; } (A)arr (B)(arr+5) (C)(arr+4) (D)Not possible Answer: (B)Explanation: Since %s is used, the printf statement will print everything starting from arr+5 until it finds ‘\\0’ Quiz of this Ques
1 min read
C | String | Question 8
Output? int main() { char a[2][3][3] = {'g','e','e','k','s','q','u','i','z'}; printf(&quot;%s &quot;, **a); return 0; } (A) Compiler Error (B) geeksquiz followed by garbage characters (C) geeksquiz (D) Runtime Error Answer: (C) Explanation: We have created a 3D array that should have 2*3*3 (= 18) elements, but we are initializing only 9 of them. In
1 min read
C | String | Question 9
Consider the following C program segment: char p[20]; char *s = &quot;string&quot;; int length = strlen(s); int i; for (i = 0; i &lt; length; i++) p[i] = s[length — i]; printf(&quot;%s&quot;, p); The output of the program is? (GATE CS 2004) (A) gnirts (B) gnirt (C) string (D) no output is printed Answer: (D) Explanation: Let us consider below line
1 min read
Practice Tags :
three90RightbarBannerImg