Search code examples
c++stringpointerstic-tac-toe

C++ - How to print this correctly?


I'm programming a small game in C++ (Tic Tac Toe), and have a problem while printing the board.

Here's the code ("syntax.h" is a header file with functions such as print, println, input):

#include "syntax.h" // contains helpful functions such as "print" and "println" to shorten code

char board[3][3];
void print_board();

int main()
{
    print_board();
}
void print_board()
{
    for (int i = 0; i < 3; i++)
    {
        println("-------");
        for (int j = 0; j < 3; j++)
        {
            print("|" + board[i][j] + " "); // ERROR - Cannot add two pointers
        }
        println("|");
    }
    println("-------");
    input();
}

print is a function in "syntax.h" that receives a string variable and prints it with cout, and then flushes the output buffer.

Now, I cannot print a string like above because it tells me I cannot add two pointers.

I understand why it happens, and thats because the "" in the print parameters are actually char* and not string variables, and I cannot add them together.

The problem is that I also don't want to make another print function call, and print all these 3 string in this same function call.

So how am I supposed to print this above without the error?


Solution

  • Instead of

    print("|" + board[i][j] + " ");
    

    Try

    print((std::string("|") + board[i][j] + " ").c_str())
    

    std::string has an overloaded operator+ for concatenation. Don't forget to

    #include <string>