MFC - several common type conversions (CString, Int, Char, string)

* Since yesterday, I plan to make a component for learning point cloud. The point cloud operation platform chooses MFC, but when adding functions to the MFC framework, it is often necessary to convert some data types. There are also a lot of information on the Internet, but I feel that it is not enough. It is comprehensive and cannot be presented to the reader at a glance to the content that the reader is looking for. Take some notes now, so that you can check it later, and I hope it can help the reader. *


1. CString to char type conversion

        //这里使用string时在MFC项目中可能会报错
        //需要在目标文件头部添加命名空间(using namespace std;)
        //若此时让然报错需要添加引用(#include "string")
        CString str = "hello";
        string st = (string)(CStringA)str;
        int len = st.length();
        char* ch = (char*)malloc(len); //动态申请char*大小的空间
        for(int i = 0 ; i <len ; i++)
        {
        ch[i] = st[i];
        }
        ch[len] = '\0';

2. Conversion of int to CString type

  /*若转换时Format函数第一个参数报错可能是因为项目字符集有问题,可以修改为“使用多字节字符集”;或者将参数"%d"改为_T("%d")*/

     int myInt;//目标int类型
     CString myCString;//目标CString类型
     myCString.Format("%d",myInt);

/*幻换函数,有俩个参数(前一个%d表示十进制正数,不加则不能将myInt格式为CString;第二个参数即为需要转换的int类型变量)*/

A brief introduction to Formt:
There are two forms, two parameters and three parameters. The three parameters are thread-safe but not commonly used. The two parameters are more commonly used and need to be mastered.

3. CString to int type conversion 

 int myInt;//目标int类型
 CString myCString;//目标CString类型
 myInt= _ttoi(myCString);

4. Int to string type conversion
The C++ function std::to_string can be used for conversion. std::to_string can not only convert int to string, but also convert common basic data types, such as float, double, long, etc.

int myInt;//目标int类型
string to_string (myInt);

5. String to int type conversion

std::string str;  //目标string类型
int myInt = std::stoi(str); 

6. char to CString type conversion

CString str ="hello";  
char * mychar =str.GetBuffer(str.GetLength());  
str.ReleaseBuffer();  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325853844&siteId=291194637