Reputation: 19152
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.
Upvotes: 3
Views: 13804
Reputation: 2554
All the examples show you how to print the argv element to the standard output. I needed the code for converting to string and I used this:
string localeCode="en-us";
if(argc>1)
{
#define LOCALELEN 50
char localeArg[LOCALELEN+1];
size_t result=-1;
wcstombs_s(&result, localeArg, LOCALELEN, argv[1], LOCALELEN);
if(result)
{
localeCode.assign(localeArg);
}
#undef LOCALELEN
}
Upvotes: 0
Reputation: 281875
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;
}
Upvotes: 19