need help with Unicode strings

Started by jk, July 11, 2005, 10:12:12 PM

Previous topic - Next topic

jk

I've tried the following
#define _UNICODE
#define UNICODE

#include <stdio.h>
#include <tchar.h>

int main(int argc, char *argv[])
{
_TCHAR buf[50];

_tcscpy(buf, _T("hello"));
_tprintf(_T("%s - %d\n"), buf, sizeof(_TCHAR));
   
  return 0;
}

and I got the output
Quoteh - 2
, It should be "hello - 2". Huh? I can't see what I am doing wrong. Thanks in advance.

Pelle

Close - but no cigar... ;-)

You must use %ls for Unicode strings - not %s.

Pelle
/Pelle

Robert Wishlaw

Using _tmain instead of main, in a modified example from above, causes the error: Unresolved external symbol '_main'


#define _UNICODE
#define UNICODE

#include <stdio.h>
#include <tchar.h>

int _tmain(int argc, _TCHAR *argv[])
{
  _TCHAR buf[50];

  _tcscpy(buf, _T("hello"));
  _tprintf(_T("%ls - %d\n"), buf, sizeof(_TCHAR));
   
    return 0;
}


Robert Wishlaw

Pelle

Not _wmain? In tchar.h (~line 22) I define _tmain to be wmain for the Unicode case (like Micro$oft) - but I havn't implemented wmain yet (in many cases main works just as well).

I put this on the list of "things to look at in the future" a few years back, so I guess the future is here... ;-)

OK - I will look at it.

Pelle
/Pelle

frankie

Pelle,
I also miss the "_ttoi" function that should be defined in <tchar.h>.
F.
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide

jk

Quote from: "Pelle"You must use %ls for Unicode strings - not %s.

That's nice, thanks. Does that mean that the code should be like this?

#ifdef _UNICODE
_tprintf(_T("%ls - %d\n"), buf, sizeof(_TCHAR));
#else
_tprintf(_T("%s - %d\n"), buf, sizeof(_TCHAR));
#endif    


Well, I'm confused. :?
Thanks again.

Pelle

Quote from: "jk"Does that mean that the code should be like this?

#ifdef _UNICODE
_tprintf(_T("%ls - %d\n"), buf, sizeof(_TCHAR));
#else
_tprintf(_T("%s - %d\n"), buf, sizeof(_TCHAR));
#endif    

Yes, since _tprintf is just a macro from tchar.h that expands to wprintf (_UNICODE defined) or printf (_UNICODE not defined) - you need something like this. The C runtime functions needs a format specifier (%s or %ls) that matches the string type.

_UNICODE is for C runtime Unicode mappings in tchar.h - you also have Windows Unicode mappings through UNICODE (without the initial underscore). If you don't need anything fancy, and it's OK to use the Windows API, you might want to look at wsprintf in this case (here %s will mean different things if UNICODE is defined or not).

Quote from: "jk"
Well, I'm confused. :?
Thanks again.
Well - it *is* confusing... just look at my explanation above...!  :shock:

Pelle
/Pelle

Pelle

Quote from: "frankie"Pelle,
I also miss the "_ttoi" function that should be defined in <tchar.h>.
F.
OK - I look at this too.

Pelle
/Pelle

jk