By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,750 Members | 1,199 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,750 IT Pros & Developers. It's quick & easy.

unsigned short array to string

P: n/a
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[i]=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[i] = dataOut[j]%10;
dataOut[j] /= 10;
}//for
}//for

Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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
Jul 23 '05 #2

P: n/a
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::ostringstream 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::ostream_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.

Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.