CString to std::cout

How to print CString to console? Trying this code, but got something like pointer is printed.

..
#include <iostream>
#include <atlstr.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{ CString a= "ddd"; cout<<a.GetString();
}
Output 00F56F0
0

3 Answers

Use following :

std::wcout << a.GetString();

Use wcout to print CString to console:

CString cs("Hello");
wcout << (const wchar_t*) cs << endl;

How to print CString to console? Trying this code, but got something like pointer is printed.

My apologies. I was not finished and got interrupted. Apparently you have to convert to a temporary CStringA (otherwise it is wide string format i.e wcout). I did not realise this until I read your message (again):

std::ostream& operator << ( std::ostream& os, const CString& str )
{ if( str.GetLength() > 0 ) //GetLength??? { os << CStringA( str ).GetString(); } return os;
}

You could as suggested of course just use wcout:

std::ostream& operator << ( std::wostream& os, const CString& str )
{ if( str.GetLength() > 0 ) //GetLength??? { os << CStringA( str ).GetString(); } return os;
}

Then use like this:

std::wcout << str << std::endl;
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like