【问题标题】:Error Reading Command Line Arguments In Win32 Console Application?在 Win32 控制台应用程序中读取命令行参数时出错?
【发布时间】:2014-02-03 11:33:07
【问题描述】:

我需要帮助,因为我在尝试读取命令行参数时没有得到预期的输出。这真的很奇怪,因为我将代码复制并粘贴到常规控制台应用程序中,它按预期工作。值得注意的是,我正在运行 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

有人知道发生了什么吗?

【问题讨论】:

  • 我猜我会说你有一个 Unicode 版本,但正在尝试打印字符串,就好像它们是 Ansi 一样。
  • @JonathanPotter that 是如何发生并仍然链接的?还是首先是这个问题(没有建立)?我同意你的看法,我只是不知道它是如何构建的。奇怪。
  • @WhozCraig:我也是,虽然不能保证这里显示的代码是实际上正在编译的代码。
  • 它正在编译中...我没有做任何重大的事情。这些是visual studio 2013提供的模板。我只是在里面写了printf。
  • @JonathanPotter 像往常一样,很好。

标签: c++ winapi command-line-arguments


【解决方案1】:

_tmain 只是一个宏,它会根据你是用 Unicode 还是 ASCII 编译而改变,如果是 ASCII,那么它将放置 main,如果是 Unicode,它将放置 wmain

如果您想要接受 Unicode 命令行参数的正确 Unicode 声明,那么您必须声明它接受这样的 Unicode 字符串:

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

你可以阅读更多关于它here

您的代码的另一个问题是 printf 需要 ASCII C 样式字符串而不是 Unicode。使用wprintfstd::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;
}

【讨论】:

  • 有什么区别?
  • 我将主要功能更改为您描述的功能,但我仍然只得到第一个字母。不过很好的链接。
  • @user2316667 检查您使用 Unicode 编译它的设置。如果使用 Visual Studio,则右键单击项目 properties 并在 General 选项卡中确保将 Character Set 设置为 Use Unicode Character set
  • 是的。它始终设置为使用 Unicode 字符集。 edit 不是我知道 - 只是看着它。而且还是同样的问题。请注意,该函数适用于 main。但我真的很好奇让它与 unicode 一起工作。我的意思是,它应该可以工作,对吧?
  • 根据链接,正如预期的那样,当我使用 main 功能时,win32 应用程序可以完美运行。这可能是对术语的完全误用,但是在 unicode 或多字节字符集中是否可以“输入”?
猜你喜欢
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 2011-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多