简体   繁体   English

C++ 将字符转换为 CString

[英]C++ Convert char to CString

before i looked at all similar threads on every forum but i didn't found a solution which works for me.在我查看每个论坛上的所有类似主题之前,我没有找到适合我的解决方案。 I'm a very beginner in C++, so please don't be to strict with me.我是 C++ 的初学者,所以请不要对我太严格。

My Problem is that i want to open a file, and read the characters with a buffers.我的问题是我想打开一个文件,并用缓冲区读取字符。 And then i want to convert them to a CString.然后我想将它们转换为 CString。

CString    buffer;

CString    temp;

...

BYTE buffer[4096] ;

        DWORD dwRead ;

        temp  = _T("");

        do
        {
            dwRead = sourceFile.Read(buffer, 4096) ;

            for (int i = 0; i < 4096; i++)
            {
                temp = temp + ((CString) (char)buffer[i]);
            }
        }

--> The problem is that the buffer just can be read asa char. --> 问题是缓冲区只能作为字符读取。 I don't know to convert it to CString.我不知道将它转换为 CString。 I read very much other stackoverflow solutions but found nothing which works for me.我阅读了很多其他的 stackoverflow 解决方案,但没有发现任何对我有用的方法。 Like the MultiByteToWideChar or something... Could somebody help me and can tell me where my fault is?像 MultiByteToWideChar 之类的......有人可以帮助我并告诉我我的错在哪里吗?

As eg explained here , you can convert the whole buffer into a CString in one go, without the inner loop:正如这里解释的那样,您可以一次性将整个缓冲区转换为CString ,而无需内部循环:

while ((dwRead = sourceFile.Read(buffer, 4096)) > 0) {
    CString block (buffer, dwRead);
    temp += block;
}

The temp = _T(""); temp = _T(""); is unneccessary;是不必要的; a default-constructed CString (ie one created like CString temp; ) is automatically an empty string.默认构造的CString (即像CString temp;那样创建的)自动是一个空字符串。

If you really need to append a single character, you could just do temp += someChar;如果你真的需要附加一个字符,你可以做temp += someChar; . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM