繁体   English   中英

将 C++ 中的数组转换为字符串

[英]Convert Array in C++ to String

我知道在 Java 中,您可以使用 Arrays.toString() 返回数组的字符串表示形式。 有没有一种方法可以在 C++ 中提供类似的 function?

如果你的意思是一个字符数组,你可以使用如下内容

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

工作示例

#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;

}

居住

C++ 不是 Java。 我建议阅读一本好的C++ 编程书籍并查看一些C++ 参考网站 注意 C++ 的各种方言(例如C++11与 C++17 不同)。

请记住 C++ arrays 是同构的:所有阵列组件都具有相同的类型。 In contrast to Java, C++ does not have a root type like Java Object class. 但是 C++ 有有趣的标准容器 注意五法则 你可以设计你的程序来让你的中央class MyRootClass class

但是,您可以轻松编写一些短代码来将数组转换为字符串。

话虽如此,您可以找到有趣的开源 C++ 库,例如POCOQt来简化您的工作。

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 (eg GCC or Clang ), your linker (eg GNU binutils ) and of your build automation (eg 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). 如果您的 C++ 代码库很大(例如数十万行 C++),请考虑编写GCC 插件以自动生成一些 C++ 代码用于序列化或打印例程代码。

将 C++ 中的数组转换为字符串

一种可能性可能是使用半标准化的文本表示,如JSONYAML (可能使用sqliteZCCDCA7F9E82EB3BC34等数据库)。 两者都有 C++ 中的开源库,这可能会有所帮助。

另请参阅s11n序列化库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM