I have a problem when handling command line arguments in a simple C++ application written in Visual Studio 2008. I have written the following code:
#include <iostream>
using namespace std;
int _tmain(int argc, char **argv)
{
char* c = *argv;
for(int i=0; i< argc ; ++i)
{
cout << argv[i] << endl;
}
int a;
cin >> a;
return 0;
}
My problem is that only the first character of each command line argument is written to cout.
I identified the cause to be that the characters in the command line arguments are represented as 2 bytes, making every other 1 byte char contain only zeros, i.e ‘\0’.
My question is, why do this happen? from what i found in samples on the net it should work as i have written it. Also, is there a way to force the characters in the arguments to be of 1 byte representation?
I hope my question is clear enough.
Your
_tmainis receiving UTF-16 characters which, when fed Latin text, have a 0 in every other byte. You are interpreting them as single byte characters. You need to interpret them as wide characters.I would write it something like this:
If you don’t want to use UTF-16 then you can stick with
charlike this:Note the change in the naming of the
mainfunction. In MS world,wmainreceiveswchar_t*andmainreceiveschar*.If you do switch to
char*then you should also update your project configuration to target MBCS rather than Unicode.More information on the main function handling of the MS compiler can be found here: main: Program Startup.