Skip to content
Related Articles
Open in App
Not now

Related Articles

std::to_string in C++

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 26 Apr, 2022
Improve Article
Save Article
Like Article

It is one of the method to convert the value’s into string.

The others are-

By using stringstream class
By using to_string() method
By using boost.lexical cast

The to_string() method takes a single integer variable or other data type and converts into the string.

Convert numerical value to string Syntax :

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

Parameters :
val - Numerical value.

Return Value :
A string object containing the representation of val as a sequence of characters.

CPP




// CPP program to illustrate
// std::to_string
#include <bits/stdc++.h>
 
// Driver code
int main()
{
    int var1=16;
       
    // Converting float to string
    std::string str1 = std::to_string(12.10);
 
    // Converting integer to string
    std::string str2 = std::to_string(9999);
   
    // Converting integer to string by taking a variable
    std::string str3 = std::to_string(var1);
 
    // Printing the strings
    std::cout << str1 << '\n';
    std::cout << str2 << '\n';
      std::cout << str3 << '\n';
    return 0;
}

Output

12.100000
9999
16

Problem : Find a specific digit in a given integer. Example :

Input : number  = 10340, digit = 3
Output : 3 is at position 3

Implementation:

CPP




// CPP code to find a digit in a number
// using std::tostring
#include <bits/stdc++.h>
 
// Driver code
int main()
{
 
    // Converting number to string
    std::string str = std::to_string(9954);
 
    // Finding 5 in the number
    std::cout << "5 is at position " << str.find('5') + 1;
}

Output :

5 is at position 3

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!