0

I'm new to C++. I know a lot of python but I'm extremely new to C++. I was creating an array of chars but I got this error- "Too many Initializers" in VSCode. Please let me know how to fix it. Here's the code

1 | class Board {
2 |     public:
3 |     char pos_list[9];
4 | 
5 |     void reset_pos() {
6 |        pos_list[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};
7 |     };
8 | };

I am getting this error in line 6. Please help me :(

rioV8
  • 24,506
  • 3
  • 32
  • 49
Hax Guru
  • 188
  • 1
  • 1
  • 10
  • There is a list of good books [here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Nov 09 '20 at 10:29
  • As a side note, I strongly recommend you use [std::array](https://www.learncpp.com/cpp-tutorial/6-15-an-introduction-to-stdarray/) as it has much more functionality and is less error-prone. At the very least it supports exactly what you want to do. `board.fill(' ')` –  Nov 09 '20 at 12:03

1 Answers1

3

EDIT: My initial answer was not correct, please find the modified correct way to do what you are looking for:

You will not be able to use {'','',''} in order to assign empty values to all elements in the array in C++, you can only do that while initializing the array when you declare it. Also, it wouldn't be ideal because it would use hardcoding of ' ' across the entire length of the array. The better way to do this is to loop over the array and then set each element to empty like below:

void reset_pos() {
           int len = sizeof(pos_list)/sizeof(pos_list[0]);
           for(int i=0; i<len; i++){
               pos_list[i] = ' ';
           }
        };
Link
  • 1,198
  • 4
  • 14
  • Hey, I'm getting another error. Expression must be a modifiable lvalue. – Hax Guru Nov 09 '20 at 09:03
  • Sorry about the initial incorrect answer, I've modified my answer, I've been doing a lot of Javascript lately which kind of threw me off as soon as I read the question :) Hope this fixes your issue. – Link Nov 09 '20 at 09:17
  • Let me know if this one works, so I can try and help you in case it doesn't. – Link Nov 09 '20 at 09:21