Monday 23 February 2015

Convert an integer (decimal) to string in C++

Welcome to Logically Proven blog.
This post demonstrates how to convert an integer to a string in C++.

There are two ways to achieve this functionality.

1) using stringstream
2)using to_string function (C++ 11)

Using stringstream: (better if you are not using latest version)

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

 string itos(int i) // convert int to string
 {
  stringstream s;
  s << i;
  return s.str();
 }

 int main()
 {
  int i = 128;
  string ss= itos(i);
  const char* p = ss.c_str();

  cout << ss << " " << p << "\n";
 }

This technique works for converting any type that you can output using <<.

Using to_string function:

Converts a numerical value to std::string

The following functions are available in string library since C++ 11 version to convert numeric to string .

std::string to_string(int value); //converts a signed decimal to string
std::string to_string(long value); //converts a signed long decimal to string
std::string to_string(long long value); //converts a signed long long decimal to string
std::string to_string(unsigned value); //converts an unsigned decimal to string
std::string to_string(unsigned long value); //converts an unsigned long decimal to string
std::string to_string(unsigned long long value); //converts an unsigned long long decimal to string
std::string to_string(float value); //converts a float value to string
std::string to_string(double value); //converts double float value to string
std::string to_string(long double value); //converts long double float value to string

These functions takes 'value' as a parameter and returns a string equivalent.

Example:

#include <iostream>
#include <string>
 
int main() 
{
    double dVal = 28.28;
    std::string d_str = std::to_string(dVal);
    std::cout << d_str << '\n';
}

//output: 28.280000

You may run into some errors in the second case if your compiler doesn't support. The error message is
"to_string is not a member of std".  In this case please follow this link how to fix -
http://stackoverflow.com/questions/12975341/to-string-is-not-a-member-of-std-says-so-g

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven
Learn, Teach, Share

Karthik Byggari

Author & Editor

Computer Science graduate, Techie, Founder of logicallyproven, Love to Share and Read About pprogramming related things.

0 comments:

Post a Comment

 
biz.