putting a vector of ints into a string

Nov 5, 2010 at 3:43pm
Hi,
I'm trying to take a vector of type int (vector<int> val;) and concatenate/stick it all into a string, so the string is a list of ints, this is what i've done:

1
2
3
4
5
6
string intclass::strg() const{
	string s;
	for (int i = 1; i <= val.size(); ++i)
	s += val[i];
	return s;
	}


as a member function of a class (I should point out that this is all in a class, and vector<int> val; is a private member of the class).
when I run this in the larger program it runs, though nothing returns from this function.
any help or direction will be more than welcome, i realize I've probably done something stupid though I can't figure out what it is. this is for a school assignment, so the scenario is fairly inflexible.
thanks in advance for any responses.

afrg
Nov 5, 2010 at 4:01pm
for (int i = 0; i < val.size(); ++i)

Notice that a string is a container of chars, so your ints will be read as if they were chars.
Last edited on Nov 5, 2010 at 4:02pm
Nov 5, 2010 at 4:26pm
Nov 5, 2010 at 4:46pm
thanks for point out that i should be < not <= the size of the vector, as we're counting up from 0 with the sqare brackets. Yes, I've noticed that my ints all come out as their ASCII counterparts. this is another problem for me to fix.
thanks for your quick replies.
Nov 5, 2010 at 4:58pm
I think std::ostringstream() is a good way to do this:
1
2
3
4
5
6
7
8
9
#include <sstream>

std::ostringstream oss;

oss << 3 << 5 << 9; // put integers into the stream

std::string str = oss.str(); // extract the string from the stream

std::cout << str << '\n'; // now the ints are in the string. 
Last edited on Nov 5, 2010 at 4:58pm
Nov 6, 2010 at 5:25pm
thanks, i'll try that. though I figured there should be a more simple mechanism to to this? (or not! as the case may be).
Topic archived. No new replies allowed.