Home » C++ STL

How to convert an integer to string in C++ STL?

C++ STL | converting an integer to string: In this article, we are going to see how we can convert an integer to string in C++?
Submitted by Radib Kar, on February 27, 2019

Converting integer to string

It's often needed to convert integer datatype to string variable. C++ has its own library function to_string(), which converts any numerical value to its corresponding string type. For example, 123 converts to "123".

First 123 is an integer, whereas "123" is string value
int i = 123;
string s = to_string(i);

to_string() Function details

Prototype:

    string to_string(int/long/long long);

Parameter: numerical value

Return type: string

Example

    Like we define and declare,

    int i=5;
    string s=to_string(i);
    if(s=="5")
        cout<<"converted to string";
    else
        cout<<"Failed to convert.";

Remember, a string variable (literal) need to be defined under "". 'a' is a character whereas "a" is a string.

Header file needed:

    #include <string>
    Or
    #include <bits/stdc++.h>

C++ program to convert an integer to string

#include <bits/stdc++.h>
using namespace std;

int main(){
	int n;

	cout<<"Input integer to convert\n";
	cin>>n;

	string s=to_string(n);

	cout<<"Converted to string: "<<s<<endl;

	return 0;
}

Output

Input integer to convert
23
Converted to string: 23





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.