Beta 2005 Visual C++

I tried writing a win32 console program which would take command line inputs.  When I try to display the command line values of argv I only see the frist letter.
The line that I try to display the value is:

printf("Program name: %s\n",argv[0]);

the output is 't'.

I am not sure what is wrong, this is a program that I have tested with 'C' and visual C++ 6.0 and it works fine.

Tongue Tied


Answer this question

Beta 2005 Visual C++

  • KraGiE

    Thanks so much for posting this reply ... it solved a problem I've been having with VC++ 2005 Express Edition.

    -Keith


  • oldrocketdog

    Try changing %s to %S.

    Most likely what is happening is that argv[0] contains a Unicode string which your printf statement is treating as an ASCII string. 

    For the ASCII characters the Unicode equivalent is the same value in the lower eight bits and zero in the upper eight bits.  So, for example, A is ASCII 0x41 and Unicode 0x0041. 

    But, Intel in their infinite wisdom build their chips little-endian so, a chunk of memory with Unicode "ABC" in it will actually be 0x41 0x00 0x42 0x00 0x43 0x00 0x00 0x00.  Treat that piece of memory as an ASCII string and it looks like A followed by null so you would only get one letter printed. 

    As a format specification upper case S means "the other string".  So, in the case of printf (which expects CHAR *) %S means treat argv[0] as if it contains a Unicode string. 

    Most likely the reason this is happening is that your project properties specify "Use Unicode Character Set" so argv is declared to be wide-char.  Visual Studio 2005 seems to have changed the default value from "Use MultiByte Character Set" to "Use Unicode Character Set".  That is a good thing (it makes the program more efficient since Windows XP etc use Unicode as their native character set) but it does make for some unexpected results as you've found.

    Strictly speaking, since argv is declared to be of type TCHAR you should really be using _tprintf and not printf.  _tprintf will either call printf or wprintf as appropriate.  So, another solution to your problem would be this...


    _tprintf (_T("%s"), argv[0]);
     


    Finally, if you don't expect to ever compile your program for multi-byte you could simplify it and solve your problem by scrapping all the TCHAR and just use wchar_t


    int _tmain(int argc, wchar_t * argv[])
    {
     wprintf (L"%s", argv[0]);

     


  • Beta 2005 Visual C++