Question about Visual C ++ argv

I have problems with Visual Studio 2008. A very simple program: printing lines sent as arguments.

Why is 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 to do this with gcc and then got whole lines.

+3
source share
2 answers

By default, it _tmainaccepts Unicode strings as arguments, but coutexpects ANSI strings. This is why it prints only the first character of each line.

If you want to use Unicode _tmain, you must use it with TCHARand wcoutas follows:

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

    return 0;
}

ANSI, main char cout :

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

    return 0;
}

: TCHAR _tmain Unicode ANSI, . UNICODE , , Unicode. UNICODE , ANSI. , Unicode ANSI- - , .

cout (ANSI) wcout (Unicode). _tcout . :

#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;
}
+19

, argv . , :

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
}
0

Source: https://habr.com/ru/post/1712380/


All Articles