2010-12-07 105 views
9

我有一个计划:C++,命令行参数没有被正确解析

int _tmain(int argc, char* argv[]) 
{ 
    std::cout << "STARTING" << std::endl; 
    std::cout << "Num inputs: " << argc << std::endl; 

    for(int i = 0; i < argc; i++) 
     std::cout << argv[i] << std::endl; 

,我希望打印出所有的命令行参数。但是,输出是这样的:

./Test.exe的hello world

STARTING 民输入:3 。 ^ h W¯¯

看来,它只是看着每个参数的第一个字符,而不是整个的char *,直到终止符。

任何人有任何想法?

其他注意事项:通过VS2008创建它,我基本上是在互联网上复制和粘贴一个应该工作的例子。我已经在bash,powershell和cmd中运行该程序。

+3

I beleive`_tmain()`expect`tchar` – ruslik 2010-12-07 21:10:47

+0

如果你在你的程序中加入了一个`main`函数,它还会发生吗? IE浏览器,您更改`_tmain`的名称后... – 2010-12-07 21:11:15

+0

相关:[http://stackoverflow.com/questions/895827/what-is-the-difference-between-tmain-and-main-in-c] (http://stackoverflow.com/questions/895827/what-is-the-difference-between-tmain-and-main-in-c) – 2013-09-02 08:35:53

回答

3

您是否正在Unicode模式下编译您的代码?

+0

这是另一个正确的答案。我改变了我的项目设置为多字节字符集,它的工作原理。谢谢! – jbu 2010-12-07 21:12:41

17

您的Visual C++项目设置为Unicode,并且您的主函数被称为_tmain。这意味着Windows会调用您的函数并传递给您Unicode字符串,但您将它们视为ANSI字符串,并使用char *类型。由于第一个Unicode字符的第二个字节为空,因此它显示为一个带有一个字符的ANSI字符串。

5

最有可能的是它与UNICODE设置编译。如果定义了UNICODE,则应该使用wcout而不是cout。所有的字符串都应该放在_T()之内。

#ifdef UNICODE 
#define tout wcout 
#else 
#define tout cout 
#endif 

int _tmain(int argc, TCHAR* argv[]) 
{ 
    std::tout << _T("STARTING") << std::endl; 
    std::tout << _T("Num inputs: ") << argc << std::endl; 

    for(int i = 0; i < argc; i++) 
     std::tout << argv[i] << std::endl; 
4

First char?这听起来像Unicode被解释为ANSI。这说得通。如果你使用_tmain,那么你必须使用TCHAR。