我有double
,格式爲xxxxx.yyyy
,例如0.001500
。將double轉換爲wstring,但必須使用科學計數法格式化wstring
我想將它轉換成wstring
,用科學記數法格式化。這是我想要的結果:0.15e-2
。
我沒有C++的經驗,所以我查了std::wstring
reference,並沒有找到任何可以做到這一點的成員函數。
我發現similar threads這裏堆棧溢出,但我只是不知道如何應用這些答案來解決我的問題,尤其是他們不使用wchar
。
我曾嘗試這種解決自己:
// get the value from database as double
double d = // this would give 0.5
// I do not know how determine proper size to hold the converted number
// so I hardcoded 4 here, so I can provide an example that demonstrates the issue
int len = 3 + 1; // + 1 for terminating null character
wchar_t *txt = new wchar_t[3 + 1];
memset(txt, L'\0', sizeof(txt));
swprintf_s(txt, 4, L"%e", d);
delete[] txt;
我只是不知道如何分配足夠大的緩衝區來存放轉換的結果。每次我得到緩衝區溢出,並且這裏的所有答案都來自類似線程估計的的大小。我真的想避免這種引入「魔術」數字的類型。
我不知道如何使用stringstream
要麼,因爲這些問題的答案並沒有轉換成double
與wstring
科學符號。
我要的只是將double
轉換爲wstring
,結果wstring
被格式化爲科學記數法。
還有一個問題:我必須爲多個'double'進行轉換,我可以重複使用相同的'wstringstream'而不是爲每個操作創建一個新的'''如果我可以重複使用'wstringstream',你可以編輯你的答案,告訴我如何?感謝您的幫助。 – AlwaysLearningNewStuff
您需要清除使用流之間的數據流,否則這些數字將會相互追加到數據流中。有關如何執行此操作的詳細信息,請參閱此SO問題:http://stackoverflow.com/questions/834622/best-way-to-empty-stringstream –