Printing an array of 2D std :: string

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 convert them to 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; } } 
+6
source share
4 answers

You send the value of tab[i] to cout , so you get the memory address.

You probably want the elements to be nested deeper, for example tab[i][j] .

+4
source

tab[i] is std::string[] - that is, an array of std::string , not std::string .

Use ranged- for instead for your output. Like the standard library containers, it works with built-in arrays:

 for (const auto &row : tab) { for (const auto &c : row) { cout << c; } cout << endl; } 
+4
source

Of course, the answers that offer a loop at the output location are correct. If you have to display the tic tac toe field in many different places in your application, you may prefer to encapsulate it. One possible solution is to have the 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 intended to give you an idea, not a source for copy-paste.

+2
source

I like it more, thank you very much!

 #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; } } } 
0
source

Source: https://habr.com/ru/post/1013104/


All Articles