0

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!

2
Contributors
3
Replies
4
Views
9 Years
Discussion Span
Last Post by Ancient Dragon
0

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";
0

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

0

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++)
...
...
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.