Open In App

std::to_string in C++

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, the std::to_string function is used to convert numerical values into the string. It is defined inside <string> header and provides a simple and convenient way to convert numbers of any type to strings.

In this article, we will learn how to use std::to_string() in C++.

Syntax

std::to_string(val);

Parameters

  • val: It is the value which we have to convert into string. It can be of any numeric data type like integer, long long, double, float, long double.

Return Value

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

Example of std::to_string()

C++
// C++ Program to show how to use std::to_string
// for converting any numerical value
#include <bits/stdc++.h>
using namespace std;

int main() {
    int num = 42;
    double pi = 3.14159;
    float fnum = 1.234f;

    // Converts integer to string
    string str1 = to_string(num);

    // Converts double to string
    string str2 = to_string(pi);

    // Converts float to string
    string str3 = to_string(fnum);

    cout << "Numbers as String: " << endl;
    cout << str1 << endl;
    cout << str2 << endl;
    cout << str3 << endl;
    return 0;
}

Output
Numbers as String: 
42
3.141590
1.234000




Next Article
Article Tags :
Practice Tags :

Similar Reads