views:

1378

answers:

1

I'm having some trouble with Visual Studio 2008. Very simple program: printing strings that are sent in as arguments.

Why does this:

#include <iostream>

using namespace std;

int _tmain(int argc, char* argv[])
{
    for (int c = 0; c < argc; c++)
    {
     cout << argv[c] << " ";
    }
}

For these arguments:

program.exe testing one two three

Output:

p t o t t

?

I tried doing this with gcc instead and then I got the whole strings.

+12  A: 

By default, _tmain takes Unicode strings as arguments, but cout is expecting ANSI strings. That's why it's only printing the first character of each string.

If you want use the Unicode _tmain, you have to use it with TCHAR and wcout like this:

int _tmain(int argc, TCHAR* argv[])
{
    for (int c = 0; c < argc; c++)
    {
       wcout << argv[c] << " ";
    }

    return 0;
}

Or if you're happy to use ANSI strings, use the normal main with char and cout like this:

int main(int argc, char* argv[])
{
    for (int c = 0; c < argc; c++)
    {
       cout << argv[c] << " ";
    }

    return 0;
}

A bit more detail: TCHAR and _tmain can be Unicode or ANSI, depending on the compiler settings. If UNICODE is defined, which is the default for new projects, they speak Unicode. It UNICODE isn't defined, they speak ANSI. So in theory you can write code that doesn't need to change between Unicode and ANSI builds - you can choose at compile time which you want.

Where this falls down is with cout (ANSI) and wcout (Unicode). There's no _tcout or equivalent. But you can trivially create your own and use that:

#if defined(UNICODE)
    #define _tcout wcout
#else
    #define _tcout cout
#endif

int _tmain(int argc, TCHAR* argv[])
{
    for (int c = 0; c < argc; c++)
    {
       _tcout << argv[c] << " ";
    }

    return 0;
}
RichieHindle