Reputation: 866
I am trying to initialize a tic-tac-toe board in c++ but the output always gives me hexa values. Is there a way to transform them into actual string values ?
#include <iostream>
#include<string>
using namespace std;
int main()
{
string tab[5][5] = { "1","|","2","|","3",
"-","+","-","+","-",
"4","|","5","|","6",
"-","+","-","+","-",
"7","|","8","|","9" };
for(int i = 0; i <= 24; i++)
{
cout << tab[i] << endl;
}
}
Upvotes: 6
Views: 508
Reputation: 2822
Of course the answers, that propose a loop at the place of output are correct. If you happen to have to output your tic tac toe field at many different places in your application, you might prefer to encapsulate that. One possible solution is to have a tic tac toe class:
struct TicTacToe : public std::array<std::array<int, 3>, 3> {
TicTacToe() :
// not sure, if the initialization will work like that
std::array<std::array<int, 3>, 3>{{0,0,0},{0,0,0},{0,0,0}}
{};
};
and then define an output operator for it:
auto operator << (std::ostream& out, const TicTacToe& field)
-> std::ostream& {
return
out << std::accumulate(std::begin(field),
std::end(field),
std::string{},
[](const std::string& a,
const std::array<int, 3> b)
-> std::string {
return
std::accumulate(std::begin(b),
std::end(b),
std::string{},
[](const std::string& a, int b)
-> std::string {
return std::string{b < 0 ?
"O" :
(b > 0 ? "X" : " ")} +
(a.empty() ? "" : "|")
}) +
(a.empty() ? "" : "\n-+-+-\n");
});
}
Please note, that I have not tested this code. It is meant to give you an idea, not a source for copy-paste.
Upvotes: 2
Reputation: 866
That's more like it thanks a lot !
#include <iostream>
#include<string>
using namespace std;
int main()
{
string tab[5][5] = { "1","|","2","|","3",
"-","+","-","+","-",
"4","|","5","|","6",
"-","+","-","+","-",
"7","|","8","|","9" };
for(int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
cout << tab[i][j];
if (j == 4)
cout << endl;
}
}
}
Upvotes: 0
Reputation: 3357
tab[i]
is a std::string[]
- that is, an array of std::string
rather than a std::string
itself.
Use ranged-for
instead for your output. As well as the Standard Library containers, it works with built-in arrays:
for (const auto &row : tab) {
for (const auto &c : row) {
cout << c;
}
cout << endl;
}
Upvotes: 4
Reputation: 12777
You're sending the value of tab[i]
to cout
, so you're getting the memory address.
You probably want to get the items nested deeper, like tab[i][j]
.
Upvotes: 4