Reputation: 5634
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?
Upvotes: 0
Views: 1504
Reputation: 9853
_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;
}
Upvotes: 3