Converting CString to Integer and Float: A Duplicate Query

There are multiple solutions to convert a string to an integer. The first solution involves using std::cin to directly take an integer input. If you prefer to use a string, you can use strcpy to copy the string to a char array and then use atoi to convert it to an integer. Another solution involves using a string library function to convert the string to an integer. Additionally, there is a method to convert a certain data type to another using a specific function. However, it is unclear if there is a similar method to convert a different data type to an integer.

Question:

I am having trouble finding a C++ solution to convert

CString

to both integer and floating point data types. Any assistance would be greatly appreciated.


Solution:


The recommended approach to achieve this in MFC while adhering to UNICODE standards is as follows:

CString sInt = _T("10");
int n = _ttoi(sInt);
CString sFloat = _T("10.1");
float f = _ttof(sFloat);

David Heffernan suggested that if your project configuration is exclusively UNICODE and you have no intention of targeting old MS OSs such as Windows 98, you may utilize the following without using MBCS.

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

In the C++11 programming language, the following can be utilized:

std::string sInt = "10";
int i = std::stoi(sInt);
std::string sFloat = "10.1";
double d = std::stod(sFloat);

Frequently Asked Questions

Posted in Uncategorized