2012-04-03 93 views
1

你會如何轉換一個字符串,讓我們說: string Numbers = "0.3 5.7 9.8 6.2 0.54 6.3";成一個浮點數組,例如:float Numbers[6] = {0.3, 5.7, 9.8, 6.2, 0.54, 6.3};如何將字符串轉換爲浮點數組?

+0

我做了一些搜索和似乎指向函數strtok,但是其他的搜索似乎在說你需要一個更多的自定義功能。也許你可以在Google上找到比我更好的答案,如果別人沒有在這裏回答。 – TecBrat 2012-04-03 01:55:20

+0

是的,那是我的想法。我打算試圖使用'strtok()'將它分解成單個字符串,然後使用'atof()'將字符串轉換爲浮點數(注意我是一名新手程序員)在字符串上。 – Sean 2012-04-03 02:02:39

回答

11

我會用數據結構和算法從std::

#include <string> 
#include <vector> 
#include <algorithm> 
#include <iterator> 
#include <iostream> 
#include <cassert> 
#include <sstream> 

int main() { 
    std::string Numbers = "0.3 5.7 9.8 6.2 0.54 6.3"; 

    // If possible, always prefer std::vector to naked array 
    std::vector<float> v; 

    // Build an istream that holds the input string 
    std::istringstream iss(Numbers); 

    // Iterate over the istream, using >> to grab floats 
    // and push_back to store them in the vector 
    std::copy(std::istream_iterator<float>(iss), 
     std::istream_iterator<float>(), 
     std::back_inserter(v)); 

    // Put the result on standard out 
    std::copy(v.begin(), v.end(), 
     std::ostream_iterator<float>(std::cout, ", ")); 
    std::cout << "\n"; 
} 
+0

你沒有使用'使用namespace std'的任何特定原因? – Sean 2012-04-03 02:11:45

+2

是的。使用名稱空間std'添加'會引入錯誤。一個好的問題描述在這裏:http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c – 2012-04-03 02:15:45

+2

@肖恩:閱讀答案[這裏](http://stackoverflow.com/questions/1265039/using-std-namespace)與最upvotes(我建議不要使用它)。 – 2012-04-03 02:17:28