要修复编写的代码,使其适用于任何编译器选项:
int main(int argc, _TCHAR* argv[])
{
cout << "argc = " << argc << "\n";
for (int i = 0; i < argc; i++)
{
cout << (char*)argv[i] << endl; // shows how broken main(_TCHAR) is
char szTemp[1024] = {0};
sprintf_s(szTemp, "%s", argv[i]); // works but... isn't wcstombs()
cout << szTemp << "\n";
// -or- much simpler:
printf("%s\n", argv[i]); // printf seems to naturally handle _TCHAR*
}
}
在漫长的周末,我意识到这一切都是错误的:
int main(int argc, _TCHAR* argv[]) // completely invalid TCHAR / char * mix
有效的选择是:
int _tmain(int argc, _TCHAR* argv[]) // project options choose char type
int main(int argc, char **argv) // always use char * for command line input
您可以通过以下四种方式使用该TCHAR
设置:
#include <iostream>
#include <io.h>
#include <fcntl.h>
#include <atlbase.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "argc = " << argc << "\n";
for (int i = 0; i < argc; i++)
{
USES_CONVERSION;
char *pszArg = T2A(argv[i]); // ATL conversion macros
cout << pszArg << endl; // I recommend this unless no ATL at all.
char szChar[1024] = {0};
size_t useless;
wcstombs_s(&useless, szChar, argv[i], 1024); // TCHAR is wchar_t only
cout << szChar << endl;
wstring ws = argv[i];
string s(ws.begin(), ws.end()); // C++ std::string TCHAR is wchar_t
cout << s.c_str() << endl;
_setmode(_fileno(stdout), _O_WTEXT); // _O_WTEXT _O_U16TEXT
wcout << argv[i] << endl; // C++ std::wcout kind of dicey...
_setmode(_fileno(stdout), _O_TEXT);
}