When to line break when printing a one dimensional array as a multidimensional one?

Jul 14, 2021 at 10:00am
Let's say I have an array char arr[64] but I want to print it linearly, breaking lines when appropriate to get a 8x8 square.
1
2
a, b, c, d, e, f, g, h //newline
i, j, k, l, m, n [...]

I've tried:

1
2
3
4
5
6
7
8
9
10
11
bool shouldBreak(unsigned int x, unsigned int W)
{
    if((x + 1) % W == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

But it does not behave as I'd expect. What's a good way to implement this?
Last edited on Jul 14, 2021 at 10:02am
Jul 14, 2021 at 10:02am
Use vector<string>
Jul 14, 2021 at 10:09am
lastchance, the char type is just an example. I'm trying to code a program that will show the slices of a 256*256*256 cube, each vertex being a color given by its 3D coordinates. I just need to know when to go down to the next line, I don't want to use a 3d vertex array.
Thanks!
Jul 14, 2021 at 10:09am
Perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <numeric>

int main()
{
	char arr[64];

	std::iota(arr, arr + std::size(arr), '0');

	for (size_t e = 0; e < std::size(arr); ++e)
		std::cout << arr[e] << ((e + 1) % 8 ? ' ' : '\n');
}



0 1 2 3 4 5 6 7
8 9 : ; < = > ?
@ A B C D E F G
H I J K L M N O
P Q R S T U V W
X Y Z [ \ ] ^ _
` a b c d e f g
h i j k l m n o

Jul 14, 2021 at 10:15am
bergjensen33 wrote:
I'm trying to code a program that will show the slices of a 256*256*256 cube, each vertex being a color given by its 3D coordinates.


If you want to be able to slice in ANY direction and use a flattened 1-d container then consider a std::valarray. It has native slicing built-in - the only one of the standard C++ containers to do so. Alternatively, you could write your own slicer for any of the other containers or simple arrays.
Jul 14, 2021 at 10:16am
Thank you both.
Jul 15, 2021 at 5:33am
Last edited on Jul 22, 2021 at 10:49pm
Jul 15, 2021 at 6:12am
Look at the size of the declared char array, a maximum of 64 characters can be stored. 64 characters that include the numeric digits and several non-alphanumeric characters.

10 numeric characters displayed, 7 non-alphanumeric chars, 26 capitalized alphabetic chars, 6 non-alphanumeric chars. That leaves space for only 15 lower-case chars.

If you wanted to print all the way to 'z' declare the char array to have space for 75 elements.

'x', 'y' and 'z' will be lonely orphans on the last line.
Topic archived. No new replies allowed.