2014-05-05 24 views
1

很新的C++,但我不能換我的頭周圍此轉換雙打的可變大小的數組wchar_t的

我得到這個數組雙打的,只是想給它做一個與其間的空間「字符串」在java中,我只是遍歷所有條目和StringBuilder.append(arr [i])。append('');

我不知道如何在C這樣做++,最好的事情我想出了是這樣的

wchar_t* getStuff(const double *arr, const int arr_size) 
{ 
    std::vector<wchar_t> result(arr_size*2); 

    for(int i = 0; i < arr_size*2; i++) 
    { 
    if (i % 2 == 0) 
     result[i] = ?; 
    else 
     result[i] = L' '; 
    } 

    return &result[0]; 
} 

我知道這不會編譯幷包含一些非C代碼。

我有點迷路,因爲我不知道一個好的轉換方法,這裏有一個指針,哪個是真正的價值。

+0

如果您在字符串中使用數字,「wchar_t」,「char」就足夠了。 – yizzlez

+0

在C++中,你不能返回一個指向局部變量的指針。相反,返回實際的容器,在這種情況下,std :: vector <>,或者更適合的std :: string或std :: wstring。編譯器優化使這種效率更高。 – sj0h

+0

是的,我知道返回的局部變量返回未定義的行爲,只是想保持簡短。我不知道爲什麼我必須使用wchar_t,我正在使用的API需要我使用wchar:D – Nozdrum

回答

1

您可以使用std::wostringstream來實現此目的。

wchar_t* getStuff(const double *arr, const int arr_size) 
{ 
    std::vector<wchar_t> result(arr_size*2); 

    for(int i = 0; i < arr_size*2; i++) 
    { 
    std::wostringstream theStringRepresentation; 
    theStringRepresentation << arr[i]; 
    // use theStringRepresentation.str() in the following code to refer to the 
    // widechar string representation of the double value from arr[i] 
    } 

    return &result[0]; 
} 

另請注意,返回局部作用域變量引用是未定義的行爲!

return &result[0]; // Don't do this! 

爲什麼不直接使用std::vector<std::wstring>代替std::vector<wchar_t>

std::wstring getStuff(const double *arr, const int arr_size) { 
    std::vector<std::wstring> result(arr_size*2); 

    for(int i = 0; i < arr_size*2; i++) 
    { 
    std::wostringstream theStringRepresentation; 
    theStringRepresentation << arr[i]; 
    // use theStringRepresentation.str() in the following code to refer to the 
    // widechar string representation of the double value from arr[i] 
    } 

    return result[0]; 
} 
+0

還有'std :: to_wstring'。 – user657267

+0

@ user657267不用擔心,THX用於添加... –

+0

難道你只是在stringstream中形成格式之後才返回theStringRepresentation.str()? – sj0h