How to convert CString to integer and float? [dupl

2019-05-26 23:01发布

问题:

This question already has an answer here:

  • Convert MFC CString to integer 10 answers

I am trying to convert CString to int and float but unable to find any C++ library function to get this done. please help.

回答1:

The proper UNICODE-compliant way of doing it in MFC is the following:

CString sInt = _T("10");
int n = _ttoi(sInt);

CString sFloat = _T("10.1");
float f = _ttof(sFloat);

As David Heffernan mentioned: If your project configuration is UNICODE only and you don't use MBCS and do not have any plans to target old MS OSs like Window 98 you can use:

CStringW s = L"10";
int i = _wtoi(s); 

In C++11 you can use the following:

std::string sInt = "10";
int i = std::stoi(sInt);

std::string sFloat = "10.1";
double d = std::stod(sFloat);