argv[0]
is always the executable's name. (Which means that argc > 0
is always true.) If you want to output wide characters (I think _TCHAR
maps to wchar_t
, BICBWT), you must not use narrow output. In C++, outputting is done using output streams. The wide console output stream is std::wcout
.
#include <iostream>
//Beware, brain-compiled code ahead!
template< typename InpIt >
void output(InpIt begin, InpIt end)
{
while(begin != end)
std::wcout << *begin++ << L'\n';
}
int _tmain(int argc, _TCHAR* argv[])
{
std::wcout << L"num arguments: " << std::argc << L'\n';
output(argv+1, argv+argc)
return 0;
}
As Rup mentions, _TCHAR
changes its value (char
or wchar_t
) depending on some definition.
First and foremost: Do you really need this switching? In practice, when you need wide characters, then most often you really need them and the program won't work correctly with narrow characters.
So it's very likely you can just settle to pure wide characters, get rid of the switching, and use the above code as written.
However, if you really need to switch, you need to switch between narrow and wide console streams yourself. (This is only true for the console stream objects, BTW. For your own streams, say, for example, file streams, you can just use _TCHAR
and let the compiler figure out the rest: std::basic_ofstream<_TCHAR>
.) One way to do this would be a traits class:
//Beware, brain-compiled code ahead!
template< typename Char >
struct console_stream_traits; // leave undefined
template<>
struct console_stream_traits<char> {
typedef std::basic_ostream<char> ostream;
typedef std::basic_istream<char> istream;
std::basic_ostream<char>& cout = std::cout;
std::basic_ostream<char>& cerr = std::cerr;
std::basic_ostream<char>& clog = std::clog;
std::basic_istream<char>& cin = std::cin;
};
template<>
struct console_stream_traits<wchar_t> {
typedef std::basic_ostream<wchar_> ostream;
typedef std::basic_istream<wchar_> istream;
std::basic_ostream<wchar_t>& cout = std::wcout;
std::basic_ostream<wchar_t>& cerr = std::wcerr;
std::basic_ostream<wchar_t>& clog = std::wclog;
std::basic_istream<wchar_t>& cin = std::wcin;
};
typedef console_stream_traits<_TCHAR> my_ostream;
typedef my_console_stream_traits::ostream my_ostream;
typedef my_console_stream_traits::ostream my_ostream;
my_ostream& my_cout = my_console_stream_traits::cout;
my_ostream& my_cerr = my_console_stream_traits::cerr;
my_ostream& my_clog = my_console_stream_traits::clog;
my_istream& my_cin = my_console_stream_traits::cin;
With that, the loop in the output()
function above would become:
while(begin != end)
my_cout << *begin++ << _T('\n');