argv参数的int main()问题

时间:2014-09-02 13:42:47

标签: c++ boost argv argc

编辑:以下代码通过Microsoft Visual Studio 2013运行

我有以下脚本:

#include "stdafx.h"
#include <iostream>
#include <boost/filesystem.hpp>

using namespace boost::filesystem;


int main(int argc, char* argv[])
{

    if (argc < 2)
    {
        std::cout << "Usage: tut1 path\n";
        return 1;
    }
    std::cout << argv[1] << std::endl;
    std::cout << "File Size is: " << file_size(argv[1]) << std::endl;


    return 0;
}

但是当我用ctrl+f5运行它时,我收到了这条消息(由代码本身的if条件预测:

Usage: tut1 path

参数的数量似乎低于2.

为什么会这样?我该如何避免这个问题?

修改

当我删除以下行时:

std::cout << "File Size is: " << file_size(argv[1]) << std::endl;

我得到&#34; Filing.cpp&#34;印在我的控制台上意味着 argv[0]值为Filing.cpp,进一步显示argv正在从项目的Debuger的命令参数中获取命令。

但是当我再次添加该行时,我会看到消息"Filing.exe not found or not built by the last incremental link;"

3 个答案:

答案 0 :(得分:4)

最简单的解决方案是在编译输出的目录中打开提示并调用程序并传入文件名字符串。

e.g。 FileSize.exe foo.jpg

这可以节省项目配置选项的混乱。

if触发因为应用程序文件名被认为是第一个参数,所以argc == 1小于2,触发指令。

答案 1 :(得分:4)

如果你像这样运行它,参数的数量只有一个(可执行文件名)。如果您正在使用Visual Studio(您可以使用它)并且想要添加参数,请转到属性 - &gt;调试并添加所需的参数&#34;命令参数&#34;

答案 2 :(得分:2)

如果要运行带参数的程序,请运行cmd的exe文件。 exe文件将在调试目录中。 在cmd中转到exe文件的路径然后运行命令,如ABC.exe然后参数。