简体   繁体   中英

Error Reading Command Line Arguments In Win32 Console Application?

I need help because I am not getting the expected output while attempting to read the command line arguments. It is really strange because I copied and pasted the code into a regular console application and it works as expected. It is worth noting that I am running Windows 7 and in visual studio I set the command line argument to be test.png

Win32 Code:

#include "stdafx.h"

using namespace std;

int _tmain(int argc, char* argv[])
{
    //Questions: why doesn't this work (but the one in helloworld does)
    //What are object files? In unix I can execute using ./ but here I need to go to debug in top directory and execute the .exe
    printf("hello\n");
    printf("First argument: %s\n", argv[0]);
    printf("Second argument: %s\n", argv[1]);

    int i;
    scanf("%d", &i);

    return 0;
}

Output:

hello
First Argument: C
Second Argument: t

I tried creating a simple console application and it works:

#include <iostream>

using namespace std;

int main(int arg, char* argv[])
{
    printf("hello\n");
    printf("First argument: %s\n", argv[0]);
    printf("Second argument: %s\n", argv[1]);

    int i;
    scanf("%d", &i);

    return 0;
}

Output:

hello
First Argument: path/to/hello_world.exe
Second Argument: test.png

Does anyone have any idea what is going on?

_tmain is just a macro that changes depending on whether you compile with Unicode or ASCII, if it is ASCII then it will place main and if it is Unicode then it will place wmain

If you want the correct Unicode declaration that accepts command line arguments in Unicode then you must declare it to accept a Unicode string like this:

int wmain(int argc, wchar_t* argv[]);

You can read more about it here

Another issue with your code is that printf expects an ASCII C Style string and not a Unicode. Either use wprintf or use std::wcout to print a Unicode style string.

#include <iostream>
using namespace std;

int wmain(int argc, wchar_t* argv[])
{
    //Questions: why doesn't this work (but the one in helloworld does)
    //What are object files? In unix I can execute using ./ but here I need to go to debug in top directory and execute the .exe
    std::cout << "Hello\n";
    std::wcout << "First argument: " << argv[0] << "\n";
    std::wcout << "Second argument: " << argv[1] << "\n";

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM