user3331346
user3331346

Reputation: 167

C++ 2d char array to string

How can you convert a 2d char array into a string?

 int main()
{
   char foo[3][3] = {{'a','b','c'}, {'d','e','f'},{'g','h','i'}};
   string bar;
   bar = foo;
   cout<< bar; //abcdefghi

 return 0;
}

also can you convert only select parts of a 2d array to a string?

 int main()
{
   char foo[3][3] = {{'a','b','c'}, {'d','e','f'},{'g','h','i'}};
   string bar;
   bar = foo[0][1] + foo[1][2] + foo[2][0];
   cout<< bar; //bfg (bar contains only b, f, and g)

 return 0;
}

Upvotes: 1

Views: 26450

Answers (4)

Sameen
Sameen

Reputation: 11

int main(){

 Char ar[4][10]=. 
  {"one","two","three","four"};


      for(int i=0;i<4;i++)
      {
           Cout<<ar[i]<<endl;

      }

return 0;
}

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227390

You can use the fact that the elements in the 2D array are contiguous, and the two-iterator constructor of std::string:

char foo[3][3] = {{'a','b','c'}, {'d','e','f'},{'g','h','i'}};
std::string bar(&foo[0][0], &foo[2][2]+1);
std::cout << bar << std::endl; // abcdefgi

Here, &foo[0][0] is a pointer to the first element, and &foo[2][2] + 1 is a pointer to one past the last one. And pointers are iterators.

Upvotes: 7

UnTraDe
UnTraDe

Reputation: 3867

The C++ standard does not contain a function to this, so you'll have to write your own.

You can use the following code:

int main(int argc, char const *argv[])
{
    char foo[3][3] = {{'a','b','c'}, {'d','e','f'},{'g','h','i'}};
    string bar;


    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            bar.append(foo[i][j]);
        }
    }

    cout << bar;

    return 0;
}

This code iterate through the 2d array, which is acually an array or arrays, and add each character to the string.

Upvotes: 0

michaeltang
michaeltang

Reputation: 2898

hope this piece of code will help, welcome to c++

#include <iostream>
using namespace std;
int main()
{
   char foo[3][3] = {{'a','b','c'}, {'d','e','f'},{'g','h','i'}};
   string bar;
   bar = "";
   for(int i =0 ; i< 3;i++)
   {
      for(int j =0 ;j<3;j++)
      {
          bar += foo[i][j];
      }
   }
   cout<< bar; //abcdefghi

 return 0;
}

Upvotes: 2

Related Questions