我从终端收到以下字符串:
"4 4 0.2 0.3 0.0 0.1 0.4 0.1 0.2 0.0 0.4 0.2 0.3 0.0 0.5">
我的目标是将此字符串保存为一个浮动数组,如arr=[4,4,0.2,…]。我事先不知道数组的大小,所以这取决于用户写的内容。这些值总是用空格分隔。
我尝试过使用std::stof(如https://www.geeksforgeeks.org/stdstof-in-cpp/),字符串流(如中所述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] != ' '; i++) {
// if str[i] is ' ' then split
if (trans_matrix[i] == ' ') {
j++;
}
else {
arr[j] = std::stof(trans_matrix[i]) // string to float
}
}
但编译器说:
调用"stof"没有匹配函数
您的代码非常混乱。代码的一半将字符串视为字符序列(这是正确的),但另一半将其视为浮点序列,这不是真的。例如
std::vector<float> arr(trans_matrix.size(), 0);
这将创建一个与字符串大小相同的向量。但是字符串大小是指与字符串中浮点数不同的字符数。还有
arr[j] = std::stof(trans_matrix[i]);
trans_matrix[i]
是一个字符,它不是字符串,所以不能在它上使用将字符串转换为浮点值的函数。
我试图明确一点,你不能通过编写大致正确的代码来编程。你必须仔细思考你正在做什么,并编写完全正确的代码。你必须对这些概念完全清楚和精确。
如果你在读std::cout
,你会怎么做?如果你从一个字符串中读取,除了使用std::istringstream
而不是std::cout
之外,这是完全相同的方法。这里有一个简单的方法。
#include <sstream>
std::vector<float> arr;
std::istringstream input(trans_matrix);
float f;
while (input >> f)
arr.pusk_back(f);
简单地说,创建一个字符串流,一次读取一个浮点值,将它们添加到向量中。