Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using printf with CString

Status
Not open for further replies.

Japhy1

Technical User
Apr 19, 2007
7
US
Hi, a simple question.

I'm try to use the printf function with CStrings in a Win32 Console application. I've already included MFC support. Since the printf function accepts const char * variables, I'm getting an error when I try something like.

CString s = "this is a test";
printf(s);

Is there another function or a conversion that will left me print CString variables to the console?

Thanks in advance for your help.
 
CString sucks. I'd use STL strings.
However, I believe you can fix your problem by calling the GetString() or GetBuffer() methods of CString.
 
both GetBuffer() and GetString() return a const wchar_t * which still doesn't work with printf, unfortunately.

You're right, CString is really starting to get on my nerves but I have to use it temporarily for this project.

 
I got it to work by doing this...

CString s = "This is a test";
CT2CA pszConvertedAnsiString (s);
std::string strStd (pszConvertedAnsiString);
printf("%s", strStd.c_str());

not very elegant but it works...
 
> both GetBuffer() and GetString() return a const wchar_t * which still doesn't work with printf,
Well it might, if you used
Code:
printf("%S", s.GetString() );  // note the CAPS 'S'

> printf(s);
Never pass an unknown string as the control string to any of the variadic functions. Just one unexpected '%' in there, and the code is in a world of trouble before you can say 'segfault'.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
yes, that works too...thanks for the response and for the pseudo-esoteric warning.
 
This will work for both MBCS and Unicode
Code:
_tprintf (_T("%s"), (LPCTSTR) s);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top