unsigned short array to string

G

greyham

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
 
V

Victor Bazarov

greyham said:
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
 
J

Jerry Coffin

greyham said:
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::eek: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::eek:stream_iterarator<short>(inter, " "));

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top