簡體   English   中英

將字符串另存為浮點數數組C ++

[英]Save string as array of floats C++

我從終端收到以下字符串:
“ 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”

您的代碼很混亂。 您的代碼一半將字符串視為字符序列(正確),而另一半則將其視為浮點序列,但這並不是真的。 例如

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);

簡單,創建一個字符串流,一次讀取一個浮點數,然后將它們添加到向量中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM