c++c-stringswchar-twchar

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.

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    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 a s a char. I don't know to convert it to CString. I read very much other stackoverflow solutions but found nothing which works for me. Like the MultiByteToWideChar or something... Could somebody help me and can tell me where my fault is?


Solution

  • As e.g. explained here, you can convert the whole buffer into a CString in one go, without the inner loop:

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

    The temp = _T(""); is unneccessary; a default-constructed CString (i.e. one created like CString temp;) is automatically an empty string.

    If you really need to append a single character, you could just do temp += someChar;.