Arjun Singh
Arjun Singh

Reputation: 101

Convert Array in C++ to String

I know in Java, you can use Arrays.toString() to return a String representation of an Array. Is there a method that serves a similar function in C++?

Upvotes: 2

Views: 7785

Answers (2)

C++ is not Java. I recommend reading a good C++ programming book and to look into some C++ reference website. Be aware of various dialects of C++ (e.g. C++11 is not the same as C++17).

Remember that C++ arrays are homogeneous: all array components have the same type. In contrast to Java, C++ does not have a root type like Java Object class. But C++ has interesting standard containers. Be aware of the rule of five. And you could design your program to have your central class MyRootClass from which every other class inherits.

However, you could easily write some short code to convert an array to a string.

That being said, you could find interesting open source C++ libraries, such as POCO or Qt, to ease your work.

You could also (and easily) write your C++ metaprogram generating the C++ code for declaring arrays and emitting code to print or output them, and you might use or improve the SWIG tool for that.

Read also the documentation of your C++ compiler (e.g. GCC or Clang), your linker (e.g. GNU binutils) and of your build automation (e.g. GNU make or ninja). If your C++ compiler is GCC, compile with all warnings and debug info, so g++ -Wall -Wextra -g (and learn to use the GDB debugger). If your C++ code base is big (e.g. several hundred thousands lines of C++) consider writing your GCC plugin to generate automatically some C++ code for serialization or printing routines.

Convert Array in C++ to String

A possibility might be to use a semi-standardized textual representation like JSON or YAML (perhaps with databases like sqlite or PostGreSQL). Both have open source libraries in C++ which could be helpful.

See also the s11n serialization library.

Upvotes: -2

asmmo
asmmo

Reputation: 7100

If you mean an array of characters, you can use something like what follows

std::vector arr {'a', 'b', 'c'};//the array
std::string str{arr.cbegin(), arr.cend()};//the generated string

Working example

#include <vector>
#include <algorithm>
#include <string>
#include <iostream>

int main(){
    std::vector arr {'a', 'b', 'c'};
    std::string str{arr.cbegin(), arr.cend()};
    std::cout << str;

}

Live

Upvotes: 1

Related Questions