【问题标题】:C++: Convert string to a vector<double>C++:将字符串转换为向量<double>
【发布时间】:2015-10-21 13:22:22
【问题描述】:

我对 C++ 比较陌生,想将数字的 char 字符串转换为双精度向量。这些字符串将具有不同的长度,但它们的长度始终是已知的。例如:

我有一个名为“myValue”的char* 字符串,它看起来像这样"0.5 0.4 1 5",并且有一个已知长度length=4

我想将此字符串转换为这样的双精度向量:

vector&lt;double&gt; Param 并给我以下输出:

Param[0]=0.5, Param[1]=0.4, Param[2]=1, Param[3]=5

【问题讨论】:

    标签: c++ string vector


    【解决方案1】:

    您可以使用std::stringstream 来完成此操作。我们会将字符串存储到stringstream 中,然后使用while 循环从中提取double 部分。

    std::stringstream ss;
    std::vector<double> data;
    char numbers[] = "0.5 0.4 1 5";
    ss << numbers;
    double number;
    while (ss >> number)
        data.push_back(number);
    

    Live Example

    由于我们使用的是标准容器,我建议使用 std::string 而不是 char [],然后我们可以更改

    char numbers[] = "0.5 0.4 1 5";
    

    std::string numbers = "0.5 0.4 1 5";
    

    【讨论】:

    • 你可以写std::stingstream ss("0.5 0.4 5")
    猜你喜欢
    • 2011-06-30
    • 2011-09-17
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    相关资源
    最近更新 更多