为什么仅传递 1 个参数时 argc returns 2?

Why does argc returns 2 when only 1 argument was passed?

我编写这段简单的代码是为了了解参数系统的工作原理。我将一个文本文件拖到 .exe 文件中,并得到 2 作为输出而不是我预期的 1。 为什么是2? Arg 1 是 .exe 本身吗?我怎样才能找到参数的文件名?

#include<iostream>
using namespace std;

int main(int argc, char* argv[])
{
    int i = 0;
    const int max = 100000;

    if (argc > 0)
    {
        cout<< argc <<endl;
    }

    cin.get(); cin.get();

  return 0;
}

还有一个问题。我在哪里可以告知如何访问每个参数和使用这些信息。我的目标是打开所有作为参数传递给 .exe 的文件。


这不是一个重复的问题,我问的是为什么当你传递 1 个参数时返回 2。 Link中的问题是另一个...

argv[0] 通常是 运行 的程序名称,并计入 argc。如果 argc >= 2,您的第一个文本文件名应该在 argv[1] 中。您可以简单地遍历它们...

for (size_t i = 1; i < argc; ++i)
    if (std::ifstream infile(argv[i]))
        ...use infile...
    else
        std::cerr << "ERROR - unable to open " << argv[i] << '\n';

对于更复杂的要求,您可能需要使用 getopt() et al if your system provides it, or the boost library equivalents

根据 C++ 标准(3.6.1 主函数)

  1. ...If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings (ntmbs s) (17.5.2.1.4.2) and argv[0] shall be the pointer to the initial character of a ntmbs that represents the name used to invoke the program or "".

要输出所有参数,您可以使用各种方法,例如

for ( char **s = argv; *s; ++s ) std::cout << *s << std::endl;

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


#include <algorithm>
#include <iterator>
//...
std::copy( argv, argv + argc, std::ostream_iterator<char *>( std::cout, "\n" ) );

main 的第一个参数始终是执行文件的名称(表示 .exe 文件名) 这就是为什么 argc 的值为 2(程序名称为 1,.txt 文件为其他) 您可以通过打印 argv[0]

来检查它