James Bond James Bond - 4 months ago 18
Linux Question

C++ - Basic Tic-Tac-Toe Program prints Blank Screen

I'm working on a basic Tic Tac Toe game in C++, as I'm a beginner, but this function prints out a messed up thing, usually either a blank screen or a messed up version of it with odd characters.
Code:

#include <iostream>
#include <string>

void printboard()
{
std::string array[9] = {"O","O","O","O","O","O","O","O","O"};


std::cout << " | | " << std::endl;
std::cout << " "; std::cout << array[2]; std::cout << " | "; std::cout << array[4]; std::cout << " | "; std::cout << array[3]; std::cout << " " << std::endl;
std::cout << " | | " << std::endl;
std::cout << "----|-----|----" << std::endl;
std::cout << " "; std::cout << array[5]; std::cout << " | "; std::cout << array[1]; std::cout << " | "; std::cout << array[3]; std::cout << " " << std::endl;
std::cout << " | | " << std::endl;
std::cout << "----|-----|----" << std::endl;
std::cout << " "; std::cout << array[7]; std::cout << " | "; std::cout << array[9]; std::cout << " | "; std::cout << array[8]; std::cout << " " << std::endl;
std::cout << " | | " << std::endl;
std::cout << " | | " << std::endl;


}

Answer

This seems to work:

#include <iostream>
#include <string>

void printboard()
{
    std::string array[9] = { "O","O","O","O","O","O","O","O","O" };

    std::cout << "    |     |    " << std::endl;
    std::cout << "  "; std::cout << array[2]; std::cout << " |  "; std::cout << array[4]; std::cout << "  |  "; std::cout << array[3]; std::cout << "  " << std::endl;
    std::cout << "    |     |    " << std::endl;
    std::cout << "----|-----|----" << std::endl;
    std::cout << "    |     |    " << std::endl;
    std::cout << "  "; std::cout << array[5]; std::cout << " |  "; std::cout << array[1]; std::cout << "  |  "; std::cout << array[3]; std::cout << "  " << std::endl;
    std::cout << "    |     |    " << std::endl;
    std::cout << "----|-----|----" << std::endl;
    std::cout << "    |     |    " << std::endl;
    std::cout << "  "; std::cout << array[7]; std::cout << " |  "; std::cout << array[6]; std::cout << "  |  "; std::cout << array[8]; std::cout << "  " << std::endl;
    std::cout << "    |     |    " << std::endl;
}

int main()
{
    printboard();
    std::system("Pause");

    return 0;
}

I noticed that your original code referenced [9] of an array of size 9, which is out of bounds (the last entry in that array would be [8]), and you included one too many spaces when aligning your boxes, so the values were skewed a bit. Hope this helps.