1

I'm brand new to C++ (my usual language is Python).

I found out from here how to print an array. I found out from here how to get a class object to cout as one of its properties. And I found out from here that the cout only works if it can access the class's property as a friend.

But, when I combine the answers, it doesn't seem to work. Here's what I've got:

#include <iostream>
using namespace std;

class TicTacToeGame {
    int board[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};

    friend std::ostream &operator<<(std::ostream &os, TicTacToeGame const &m);
};

std::ostream &operator<<(std::ostream &os, TicTacToeGame const &m) {
    for (int i = 0; i++; i < 9) {
        os << m.board[i];
    }
    return os;
}

int main()
{
    TicTacToeGame game;
    cout << game;
    return 0;
}

And nothing prints on the screen.

What I'd like to see is something along the lines of {0, 0, 0, 0, 0, 0, 0, 0, 0}, but fancy formatting isn't needed as long as I can see the array.

How can I get that to happen?

Pro Q
  • 4,391
  • 4
  • 43
  • 92
  • You should output a newline or `endl` after `cout << game` – M.M May 23 '18 at 02:07
  • @M.M why should I do that? – Pro Q May 23 '18 at 02:11
  • 1
    Standard output is line-buffered by default so any partial line may never appear on your screen; it depends on the OS and calling environment – M.M May 23 '18 at 02:15
  • It looks like my answer does that (accidentally) already. Thank you for letting me know that I should keep it like that. – Pro Q May 23 '18 at 02:16
  • You need to have at least one more warning enabled: my compile of your code generates: "warning: for increment expression has no effect [-Wunused-value]" – 2785528 May 23 '18 at 03:27
  • @DOUGLASO.MOEN I'm coding in Atom and using a compiler under the hood so I'm not seeing any of those warnings. Thanks for letting me know. – Pro Q May 23 '18 at 03:59

2 Answers2

3

Fix the for loop.

for (int i = 0; i++; i < 9) {

should be

for (int i = 0; i < 9; i++) {
user253751
  • 57,427
  • 7
  • 48
  • 90
1

Thank you to @immibis for reminding me how to do for loops again. (I haven't had to do those in so long...)

Here's the fancier version of the operator function that I decided to go with for the time being, so that it prints out like a tic-tac-toe board.

std::ostream &operator<<(std::ostream &os, TicTacToeGame const &m) {
    for (int i = 0; i < 9; i++) {
        os << m.board[i];
        if (i%3!=2) {
            os << " ";
        }
        if (((i+1) % 3) == 0) {
            os << "\n";
        }
    }
    return os;
}
Pro Q
  • 4,391
  • 4
  • 43
  • 92