×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

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 in C++ STL

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

Syntax

string to_string(int/long/long long);

Parameter

numerical value

Return value

The return type of this function is "string".

Here is an example with sample input and output:

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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.