Hello, i have rather curious question,

i have an array of integers, but i need/want to put them as a single strings which separates the rows with newline characters...

does anybody have any idea on how to create a string from an array of integers?

please, and thank you!

Recommended Answers

All 3 Replies

one way would be to use a stringstream object

#include <sstream>
...
...
#define SZARRAY(x) (sizeof(x) / sizeof(x[0])

int array[] = {1,2,3,4,5};
string str;
streamstring stream
for(int i = 0; i < SZARRAY(array); i++)
   stream << arrray[i] << " ";

str = stream.str() + "\n";

is there a way that you can quickly describe what you are doing as the #define portion completely confuses me

All it is doing is calculating the number of elements in the array. sizeof(array) returns the size, in bytes, of the entire array. For example if the array has 5 elements then 5 * sizeof(int) = 20 on most 32-bit compilers. Then the sizeof(array[0]) returns the size of one element of the array. Since all elements of arrays must be the same size, which all we have to do to calculate how many elements are in the array is to divide 40 by the size of the first element, which again sizeof(int) is 4 on most 32-bit compilers.

But in your actual program you may not need that macro at all. For instance you can do something like this:

const int arrayElements = 5;
int array[arrayElements]= {0}
for(i = 0; i < arrayElements; i++)
...
...
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.