Rhyous's 127.0.0.1 or ::1

October 1, 2009

How to convert an int to a string in C++? (Also doubles, floats, etc…)

Filed under: C/C++ — rhyous @ 3:28 am

Here is how I do it. This procedure actually works for any type such as: int, double, float, etc…

Convert an Int Only

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
	int i = 10;
	string s = inToString(i);
	return 0;
}

string intToString(int inInt)
{
	stringstream ss;
	string s;
	ss << inInt;
	s = ss.str();
	return s;
}

As a Template So It Works with All Types (int, float, double, etc…)

I found a comment on another guys blog that actually makes it work for any type such as double, float, etc.. It has this code using this template.
http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/

template <class T>
string anyTypeToString(const T& t)
{
	std::stringstream ss;
	ss << t;
	return ss.str();
}

This works really well, I have been using it and it is so simple.

Key words:
int to string
intToString
double to string
doublToString
float to string
floatToString

2 Comments »

  1. [...] double, etc) Filed under: Coding — rhyous @ 9:36 pm Ok, so I already have a post on How to convert an int to a string in C++? (Also doubles, floats, etc…) and so I need a post on doing this in [...]

    Pingback by How to convert a string to an int in C++? (Or to a float, double, etc) « Rhyous's 127.0.0.1 or ::1 — October 24, 2009 @ 12:28 am | Reply

  2. [...] How to convert an int to a character array when you don’t have access to the C++ Standard Library? Filed under: Coding — rhyous @ 3:44 am Ok, so I have a great way to convert and int (or any other type) to a string using the stringstream from the standard library. This is listed here: How to convert an int to a string in C++? (Also doubles, floats, etc…) [...]

    Pingback by How to convert an int to a character array when you don’t have access to the C++ Standard Library? « Rhyous's 127.0.0.1 or ::1 — November 2, 2009 @ 3:44 am | Reply


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.