读取 float 并插入到 const char * 数组

Read float and insert to an array of const char *

我从一个文本文件中读取了几个值,例如

const float vLowCut   = cfg.get<float>("LowCut");
const float vLowCut1   = cfg.get<float>("LowCut1");
...

如何将它们追加到 const char 数组中,例如

const char * CutList[2] = {"value"+vLowCut, "value2"+vLowCut2)

当然上面这行不行,只是想演示一下我想要的东西。 谢谢

这里很难使用const char *,因为你需要创建一个数组让它指向。 C++ 惯用语会更方便:

std::string CutList[2] = {
    "value" + std::to_string(vLowCut),
    "value2" + std::to_string(vLowCut2)
};

我们这样使用 to_string() 函数:

std::string CutList = {"value: "+ std::to_string(vLowCut), " value2: " + std::to_string(vLowCut2))

您是否考虑过使用 std::string?您可以使用 std::to_string:

std::string CutList[2] = {"value" + std::to_string(vLowCut), 
                          "value2" + std::to_string(vLowCut2));

如果你想使用显式格式说明符,你可以使用 std::stringstream 代替,即像这样:

#include <iostream>
#include <string>
#include <iomanip>

auto my_float_to_string = 
   [](float f){ std::stringstream ss; 
                ss << std::setprecision(3) << f;
                return ss.str(); };
std::string CutList[2] = {"value" + my_float_to_string(vLowCut), 
                          "value2" + my_float_to_string(vLowCut2));

您可以使用 c_str() 将其转换回 const char*:

strstr(CutList[0].c_str());

但不要使用c_str()作为永久存储,一旦std::string对象被销毁它就会被销毁。即:

void f(int a) {
    const char* s = nullptr;
    if(a == 10) { 
        s = std::string("aaaa").c_str(); }
    // Here s may point to invalid data because
    // corresponding std::string object has been destroyed
}