Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a 2D std::string array

Tags:

c++

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;
    }
}
like image 678
uwponcel Avatar asked Dec 12 '16 18:12

uwponcel


People also ask

How do you declare a 2D array of strings in C++?

You can declare a multidimensional array of strings like this: std::string myArray[137][42];

How do you initialize a two-dimensional string in C++?

Initialization of two-dimensional array A better way to initialize this array with the same array elements is given below: int test[2][3] = { {2, 4, 5}, {9, 0, 19}}; This array has 2 rows and 3 columns, which is why we have two rows of elements with 3 elements each.

How to input 2D array Cpp?

Taking 2D Array Elements As User Input For the above code, we declare a 2X2 2D array s . Using two nested for loops we traverse through each element of the array and take the corresponding user inputs.


2 Answers

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].

like image 187
TankorSmash Avatar answered Sep 28 '22 16:09

TankorSmash


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;
}
like image 24
Jack Deeth Avatar answered Sep 28 '22 17:09

Jack Deeth