Initializing a Two Dimensional Array of Strings

How to declare a two dimensional array of strings in c++? And also how to write this string on files?

1

6 Answers

Declaration and initialization together:

std::string myarray[2][3] = {
  { "hello", "jack", "dawson" }, 
  { "hello", "hello", "hello" }
};

For writing to file, templatetypedef's answer is almost fine, except you should do error checking and close the output file stream when done.

typedef std::vector<std::string> StringVector;
typedef std::vector<StringVector> StringVector2D;
StringVector2D twoD;
for (StringVector2D::iterator outer = twoD.begin();  outer != twoD.end();  ++outer)
    for (StringVector::iterator inner = outer->begin();  inner != outer->end();  ++inner)
        std::cout << *inner << std::endl;

You can declare a multidimensional array of strings like this:

std::string myArray[137][42];

Of course, substituting your own width/height values for 137 and 42. :-)

There's no "one right way" to write this array to disk. You'll essentially be iterating over the array writing one string at a time to disk, with some sort of appropriate separators and error-checking logic. Here's one naive implementation, which writes out one string per line (assuming that the strings don't have any newlines in them):

std::ofstream output("result.txt");
for (size_t i = 0; i < 137; ++i)
    for (size_t j = 0; j < 42; ++j)
        output << myArray[i][j] << std::endl;

Hope this helps!

2
#include<iostream>
#include<vector>
using namespace std;

  main()
  {
  vector< vector<string> > m2m;
  vector<string> A, B;
  vector< vector<string> >::iterator inter_i;
  vector<string>::iterator inter_j;

  A.push_back("micro");
  A.push_back("soft");
  A.push_back("bilgates");
  B.push_back("linux");
  B.push_back("unix");
  B.push_back("ken dennish");

  m2m.push_back(A);
  m2m.push_back(B);


  cout<<endl<<" USing iterator : "<<endl;

    for(inter_i=m2m.begin();inter_i!=m2m.end();inter_i++)
    {
      for(inter_j=(*inter_i).begin();inter_j!=(*inter_i).end();inter_j++)
       {
         cout<<*inter_j<<"       ";
       }
       cout<<endl;
    }

  return 0;
  }

I assume, that You've QString type. This should work to std::string and even (char*) properly.

QString ** myTwoDimensionalArray;

myTwoDimensionalArray = new QString*[size_x];
for(int i=0; i<size_x; i++) myTwoDimensionalArray[i] = new QString[size_y];

That's it. Now, You can write something like:

myTwoDimensionalArray[x][y] = "Hello, World!";

This will create a 2D string object of string:

String str[no of strings];
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest