2009-05-27 129 views
12

如何在C++中將CString轉換爲double如何將CString轉換爲C++中的double?

Unicode支持也不錯。

謝謝!

+0

我真的不能相信這個問題還沒有被問到......但搜索沒有透露。如果它是重複的,請溫和:) – 2009-05-27 16:43:42

+4

無法在這裏找到答案,但使用谷歌搜索「cstring加倍」可以讓您在第一次擊中時獲得正確答案。 – 2009-05-27 16:52:03

+0

@AndrewBainbridge確實如此,如果通過「正確的答案」,你的意思是這個頁面在這裏:) – aquirdturtle 2016-07-17 20:05:59

回答

25

CString可以轉換爲LPCTSTR,這基本上是一個const char*(以Unicode const wchar_t*構建)。

知道了這一點,你可以用atof()

CString thestring("13.37"); 
double d = atof(thestring). 

...或Unicode版本,_wtof()

CString thestring(L"13.37"); 
double d = _wtof(thestring). 

...或同時支持Unicode和非Unicode版本。 ...

CString thestring(_T("13.37")); 
double d = _tstof(thestring). 

_tstof()是一個擴展到atof()_wtof()基於_UNICODE是否被定義)

1

strtod(或wcstod)會將字符串轉換爲雙精度值。

(需要<stdlib.h><wchar.h>

4

與升壓lexical_cast的圖書館,你做

#include <boost/lexical_cast.hpp> 
using namespace boost; 

... 

double d = lexical_cast<double>(thestring); 
5

您可以使用std::stringstream東西轉換成任何東西。唯一的要求是要實施運營商>><<。 Stringstreams可以在<sstream>頭文件中找到。

std::stringstream converter; 
converter << myString; 
converter >> myDouble;