[英]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++ 庫,例如POCO或Qt來簡化您的工作。
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++ 中的數組轉換為字符串
一種可能性可能是使用半標准化的文本表示,如JSON或YAML (可能使用sqlite或ZCCDCA7F9E82EB3BC34等數據庫)。 兩者都有 C++ 中的開源庫,這可能會有所幫助。
另請參閱s11n序列化庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.