获取一行字符串并转换为浮点列表

时间:2016-05-04 11:34:41

标签: c++ string

我需要实现以下目标:

"4 5 1.3 0 3.1"

这是我将从用户读取的输入字符串,在阅读后我需要根据[0]字符的大小将此字符串转换为浮点列表,例如列表将是

array[4] = [5.0,1,3,0.0,3.1]

我如何实现它我尝试使用getline但是没有用。提前谢谢。

2 个答案:

答案 0 :(得分:0)

string line = "4 5 1.3 0 3.1"; // input string
istringstream stream(line); // parser
unsigned count; // how many values
double* values;
if (stream >> count) {
    values = new double[count];
    for (unsigned ii = 0; ii < count; ++ii) {
        stream >> values[ii]; // read one
        if (!stream) {
            throw std::runtime_error("not enough numbers");
        }
    }
} else {
    throw std::runtime_error("no count at start of line");
}

// do something with values...

delete[] values;

答案 1 :(得分:0)

首先将计数读入无符号整数,然后从0循环到计数,读入双精度数。要读入数组,首先动态分配一个正确的大小。更好的是,使用std::vector,它将为您处理分配。

#include <iostream>
#include <memory>
#include <sstream>
#include <string>

int main() {
    std::string line;
    std::getline(std::cin, line);

    std::istringstream ss(line);

    size_t  num_values = 0;
    if (! (ss >> num_values) ) {
        std::cerr << "Could not read the integer number of values!\n";
        return 1;
    }

    auto values = std::make_unique<double[]>(num_values);
    double tmp;
    for (size_t idx = 0; idx < num_values; ++idx) {
        if (! (ss >> values[idx])) {
            std::cerr << "Could not convert the " << idx << "th value!\n";
            return 1;
        }
    }

    // Validate solution: print the contents of the vector
    for (size_t idx = 0; idx < num_values; ++idx) {
        std::cout << values[idx] << " ";
    }
    std::cout << "\n";
}

[live example]

此解决方案使用动态分配的数组,并通过调用std::unique_ptr创建std::make_unique来确保正确清理其内存。