-1

我从终端收到以下字符串:
“4 4 0.2 0.5 0.3 0.0 0.1 0.4 0.4 0.1 0.2 0.0 0.4 0.4 0.2 0.3 0.0 0.5”
我的目标是将此字符串保存为浮点数组,如 arr=[4,4,0.2 ,...]。我事先不知道数组的大小,所以取决于用户写的内容。这些值始终由空格分隔。

我曾尝试使用 std::stof(如https://www.geeksforgeeks.org/stdstof-in-cpp/)、stringstream(如https://www.geeksforgeeks.org/converting-strings-numbers- cc/),但它们都不起作用。

试验:

cout << "Introduce the transition matrix \n";
getline (cin, trans_matrix);
std::vector<float> arr(trans_matrix.size(), 0);
int j = 0, i;
// Traverse the string
for (i = 0; trans_matrix[i] != '\0'; i++) {
    // if str[i] is ' ' then split
    if (trans_matrix[i] == ' ') {
        j++;
    }
    else {
        arr[j] = std::stof(trans_matrix[i]) // string to float
    }
}

但是编译器说:

调用“stof”没有匹配的函数

4

1 回答 1

1

Your code is quite mixed up. Half your code treats a string as a sequence of characters (which is correct) but the other half treats it as a sequence of floats which is not really true. For instance

std::vector<float> arr(trans_matrix.size(), 0);

this creates a vector the same size as the string. But the string size is the number of characters which is not the same as the number of floats in the string. Also

arr[j] = std::stof(trans_matrix[i]);

trans_matrix[i] is a character, it's not a string, so you can't use a function on it which converts a string to a float.

I'm trying to make it clear that you can't program by writing code that's approximately right. You have to think carefully about what you are doing and write code that is exactly right. You have to be completely clear and precise about the concepts.

How would you do this if you were reading from std::cout? Well it's exactly the same way if you are reading from a string except you use a std::istringstream instead of std::cout. Here's one straightforward way.

#include <sstream>

std::vector<float> arr;
std::istringstream input(trans_matrix);
float f;
while (input >> f)
    arr.pusk_back(f);

Simple, create a string stream, read the floats one at a time, add them to the vector.

于 2019-01-19T15:37:04.157 回答