简体   繁体   English

在Win32控制台应用程序中读取命令行参数时出错?

[英]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 值得注意的是,我正在运行Windows 7,在Visual Studio中,我将命令行参数设置为test.png。

Win32 Code: 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;
}

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 _tmain只是一个宏,它会根据您使用Unicode还是ASCII进行编译而变化,如果是ASCII则将放置main ,如果是Unicode则将放置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: 如果您想要正确的Unicode声明以Unicode形式接受命令行参数,则必须声明它以接受Unicode字符串,如下所示:

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. 您的代码的另一个问题是printf需要ASCII C样式字符串而不是Unicode。 Either use wprintf or use std::wcout to print a Unicode style string. 使用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.

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