0

what is the easiest way to copy a two-dimensional array of chars into a one-dimensional array of strings in c++?

something like that:

    char inCharArray[3][255];
    string outStringArray[3];

    for (int i = 0; i < sizeof(inCharArray) / sizeof(inCharArray[i]); i++)
    {
        outStringArray[i] = inCharArray[i];
    }

Regards Tillman

7
  • 1
    /*const*/std::string outStringArray[3]{inCharArray[0], inCharArray[1], inCharArray[2]};? Commented Mar 15, 2021 at 14:19
  • 1
    /*const*/ std::vector<std::string> outStringArray(std::begin(inCharArray), std::end(inCharArray));? Commented Mar 15, 2021 at 14:19
  • 1
    std::copy(std::begin(inCharArray), std::end(inCharArray), std::begin(outStringArray));? Commented Mar 15, 2021 at 14:22
  • These assume C-strings. While a C-string is always an array of characters, the inverse is not always true. OP should clarify. Commented Mar 15, 2021 at 14:24
  • 1
    I love how OP was asked specifically about inCharArray and answered with outStringArray. Classic. Commented Mar 15, 2021 at 15:00

2 Answers 2

1

Using STL algorithm is one of the best way to do it.

char inCharArray[3][255];
string outStringArray[3];

std::transform(
    std::begin(inCharrArray),
    std::end(inCharArray),
    std::begin(outStringArray),
    [](char const* c_str) -> std::string {
        return std::string{c_str};
    }
);

This is assuming the strings are ending sooner than 255.

Sign up to request clarification or add additional context in comments.

Comments

0

This alternative to std::transform is more readable to me:

std::copy(std::begin(inCharArray),
          std::end(inCharArray),
          std::begin(outStringArray));

// only safe if input strings are null-terminated and arrays have equal size
static_assert(std::size(inCharArray) == std::size(outStringArray),
              "arrays are not equal size");

Also consider using std::array instead of C-style arrays while you're writing C++ code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.