array to string
Jan 21, 2012 at 5:18pm UTC
Hey guys
I'm trying to convert to array of integers to string. You can see the function that I have created below. It works for an array with all one digit elements. eg-{1, 2, 3, 4}
but when there are two- or more digits number in that array the string will be with one digit element. for eg - {12, 3, 6}
the string will be [1,2,3,6]
Does anyone have solution to it? Is there any better way to convert int to string than using sstream?
Thx in advance :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#include <iostream>
#include <sstream>
string toString(int a[], unsigned int len)
{
string stray = "[" ;
string helper = "" ;
stringstream out;
for (int j=0; j < len; j++){
out << a[j];
helper = out.str();
}
for (int i=0; i < ((helper.length())-1); i++){
stray += helper[i];
stray += ", " ;
}
stray += helper[helper.length()-1];
stray += "]" ;
return stray;
}
int main()
{
int b[] = {1, 2, 3, 4, 5, 6, 9, 21};
cout <<toString(b, 8);
}
Jan 21, 2012 at 5:39pm UTC
You don't really need that helper, do you?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
std::string toString( const int a[], std::size_t len )
{
if ( len == 0 ) return "[]" ;
std::string result = "[" ;
for ( std::size_t i = 0 ; i < len ; ++i )
{
std::ostringstream stm ;
stm << a[i] ;
result += stm.str() + ", " ;
}
// remove the last ", " and add a ']'
return result.substr( 0, result.size()-2 ) + ']' ;
}
Jan 21, 2012 at 11:24pm UTC
Thx mate!
the "helper" is indeed not required. "helper" can only help when that is a one digit array :)
Jan 22, 2012 at 4:04am UTC
My bad; should have lifted the stream out of the loop.
1 2 3 4 5 6 7 8 9 10 11 12
std::string toString( const int a[], std::size_t len )
{
if ( len == 0 ) return "[]" ;
std::ostringstream stm ;
stm << '[' ;
for ( std::size_t i = 0 ; i < len ; ++i ) stm << a[i] << ", " ;
std::string result = stm.str() ;
// remove the last ", " and add a ']'
return result.substr( 0, result.size()-2 ) + ']' ;
}
Topic archived. No new replies allowed.