[英]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.