[英]How to get std::string from command line arguments in win32 application?
[英]Error Reading Command Line Arguments In Win32 Console Application?
我需要帮助,因为在尝试读取命令行参数时没有得到预期的输出。 确实很奇怪,因为我将代码复制并粘贴到了常规控制台应用程序中,并且可以按预期工作。 值得注意的是,我正在运行Windows 7,在Visual Studio中,我将命令行参数设置为test.png。
Win32代码:
#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;
}
输出:
hello
First Argument: C
Second Argument: t
我尝试创建一个简单的控制台应用程序,它的工作原理是:
#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;
}
输出:
hello
First Argument: path/to/hello_world.exe
Second Argument: test.png
有人知道发生了什么吗?
_tmain
只是一个宏,它会根据您使用Unicode还是ASCII进行编译而变化,如果是ASCII则将放置main
,如果是Unicode则将放置wmain
如果您想要正确的Unicode声明以Unicode形式接受命令行参数,则必须声明它以接受Unicode字符串,如下所示:
int wmain(int argc, wchar_t* argv[]);
您可以在这里了解更多信息
您的代码的另一个问题是printf
需要ASCII C样式字符串而不是Unicode。 使用wprintf
或使用std::wcout
打印Unicode样式字符串。
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.