我从终端收到以下字符串:
“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”没有匹配的函数