少し助けが必要です。質問は非常に単純ですが、私の限られた知識で申し訳ありません。1D double 配列をこのような char 行列に変換したい..たとえば、double 行列の最初の要素は
double version[6];
char version_ch[6][6];
version[0]=1.1587
version[0] を version_ch[0][5] などに変換したい。各バージョン変数は 6 桁です。誰か助けてください。
前もって感謝します。
これはどう:
const size_t num_versions = 6;
std::array<double, num_versions> version;
version[0] = 1.1587;
// ...
std::array<std::string, num_versions> version_str;
std::transform(std::begin(version), std::end(version), std::begin(version_str),
[](const double& value) { return std::to_string(value); });
std::array
、、、ラムダ式およびについて読んstd::string
でください。std::transform
std::to_string
要求する char 配列が実際に必要な場合は、次のように生成できます。
#include <cstdio>
#include <cstring>
// ...
static const size_t VERSION_N_ELEM = 6;
static const size_t VERSION_STR_LEN = 6;
double version[VERSION_N_ELEM];
char version_ch[VERSION_N_ELEM][VERSION_STR_LEN];
char buf[32];
for (int i = 0; i < VERSION_N_ELEM; ++i) {
sprintf(buf, "%.4f", version[i]);
strncpy(version_ch[i], buf, VERSION_STR_LEN);
}
これはC++よりもACアプローチですが、繰り返しになりますが、あなたのように配列を使用することは、とにかくC++よりもACアプローチです。ここでの sprintf の使用は完全に安全というわけではありません。コンパイラ ライブラリに sprintf_s または snprintf がある場合は、それを使用することを検討する必要があります。またはスティングストリームを使用します。
意図された目的についてはほとんど言わないので、十分なスペースがないため、char 'matrix' 内の文字列が null で終了しない可能性があることに注意してください。
あなたが求めているのは、C ++での単純な悪い設計です。たとえば、次のコードで結果を取得できます。
#include <sstream>
#include <iostream>
#include <string>
using namespace std;
int main(){
double version[4] = {1.2, 3.4, 5.6, 7.8};
char version_ch[4][3];
for(unsigned int i = 0; i < 4; i++){
stringstream ss;
ss << version[i];
string tmp_str = ss.str();
for(unsigned int j = 0; j < 3; j++){
version_ch[i][j] = tmp_str.c_str()[j];
}
}
}
しかし、真剣に、設計を修正する必要があります。