0

The input can be only 5, 7 or 9. Lets say in this case the input is 5, so the program generates 5 * 4 letters: "D E C B E D E D B D E D A C B E A A C B", now i need to put them into arrays of 4, so 5 char arrays, but I don't know how to do that. Here's how i generate the letters. I put all generated ones in one char array, but I also don't know how to separate it into smaller char arrays of 4. Another problem is, as I mentioned, the input changes in every run, but can be either 5, 7 or 9, so the program doesn't know how many arrays of 4 will it need.

I can't use vectors and can only use standard library because of the terms.

for (int i = 0; i < (input * 4); ++i) {
    int n = (rand() % 5) + 1;
    char kar = (char) (n + 64);
    letters[i] = kar;
}

Here is how i print it, if I put all generated letters in one array:

for (int j = 0; j < input* 4; ++j) {
    if (j % 4 == 0) {
        cout << "\nLetters in the " << (j / 4) + 1 << ". array: ";
    }
    cout << letters[j] << " ";
}

I need the output like this as it is now, but with separated arrays.

Letters in the 1. array: D E C B
Letters in the 2. array: E D E D
Letters in the 3. array: B D E D
Letters in the 4. array: A C B E
Letters in the 5. array: A A C B
  • 1
    If the input can be maximum 9, then I'd just declare a 2D array of 9 by 4. `char letters[9][4];` Now you always have 9 arrays of 4, which is always enough. – john Apr 04 '20 at 18:27

1 Answers1

2

All you need are nested arrays, like this letters[][].

However, you can't have variable sized arrays in c++. But you have an upper bound of 9, so you can do

char letter[9][4];
for (int i = 0; i < input; ++i)
  for (int j = 0; j < 4; ++j)
    letter[i][j] = ...

I would recommend using std::vector though. You requirement of "I can't use vectors and can only use standard library because of the terms." seems contradictory.

Also, avoid the c-style cast here (char) (n + 64). Prefer to do static_cast<char>(n + 64).

Also, rand() is not a recommended way to generate random numbers. See this for an example of how to generate random numbers well.

cigien
  • 57,834
  • 11
  • 73
  • 112
  • If this is in a function, would it be better if the first [] would be the declaration, so it always be the input variable? – Péter Pintér Apr 04 '20 at 19:12
  • Do you mean something like `letters[input][4]`? That's not possible. – cigien Apr 04 '20 at 19:14
  • Not exactly. So basically it's a board game, and the input is the number of the players. And from that, I created a variable and it depends on the players, and that's how many array is needed. So I create a function, and the declaration is an integer, and when I call the function, I use the variable which also is an integer, for the parameter. – Péter Pintér Apr 04 '20 at 19:18
  • I'm not sure exactly what you need. You should edit your question if it's incomplete. – cigien Apr 04 '20 at 19:19
  • Nevermind, I think I can continue it from here. Thanks. – Péter Pintér Apr 04 '20 at 19:41