unsigned short array to string

Discussion in 'C++' started by greyham, Feb 11, 2005.

1. greyhamGuest

This is a beginner question but is there a better way to do this? I
have an array of unsigned shorts and need to convert it into a string
array with the numbers separated by spaces. I've started to make an
intermediate string of characters that represents the digits. Am I on
the right track? I know java so there must be a simple way in C++ that
I don't know about since I'm new to the C++ world. Thanks for the
help!

int i=0;
int j=0;
const int DataLengthPerChannel=4;
const int maxDigits = 8;
unsigned short dataOut[DataLengthPerChannel];
short digit[maxDigits];

//initialize data
for (i=0; i<DataLengthPerChannel; i++) {
dataOut=200*i+74;
}
//first loop around every element of dataOut
//then loop around the digits of the numbers
for (j=0; j<DataLengthPerChannel; j++) {
for (i=maxDigits-1; i>=0; i--) {
digit = dataOut[j]%10;
dataOut[j] /= 10;
}//for
}//for
greyham, Feb 11, 2005

2. Victor BazarovGuest

greyham wrote:
> This is a beginner question but is there a better way to do this? I
> have an array of unsigned shorts and need to convert it into a string
> array with the numbers separated by spaces.

You need to get your spec straight. It's either a string array (where
each element is a representation of the respective element of the other
array) or it's a single string with numbers separated by spaces.

Take a look at 'ostringstream' class. You can simply output all your
shorts into one array and then get the string out of it.

> [...]

V
Victor Bazarov, Feb 11, 2005

3. Jerry CoffinGuest

greyham wrote:
> This is a beginner question but is there a better way to do this? I
> have an array of unsigned shorts and need to convert it into a string
> array with the numbers separated by spaces. I've started to make an
> intermediate string of characters that represents the digits. Am I
> on the right track? I know java so there must be a simple way in C++
> that I don't know about since I'm new to the C++ world. Thanks for
> the help!

I'm not entirely sure I understand what you want, but if my guess is
correct, you're looking for something like this:

std::vector<short> dataout;
std:stringstream inter;

// create the data
for (int i=0; i<DataLengthPerChannel; ++i)
dataout.push_back(200*i+74);

// format the data
std::copy(dataout.begin(), dataout.end(),
std:stream_iterarator<short>(inter, " "));

// get the formatted output as a string.
std::string concatenated_output = inter.str();

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jerry Coffin, Feb 11, 2005