如何向C++应用程序传递参数

3

在Java中,可以使用void main(String[] args)来传递参数。

在Eclipse中找到运行配置(run configuration),添加参数并运行程序。但是,在C++中只有int main(),如何在Visual Studio 2010中传递参数给程序呢?

3个回答

8

虽然 int main() 是正确的,但你可以使用 int main(int argc, char *argv[]) 或者 int main(int argc, char **argv) 来获取参数计数,其中 argc 是参数计数,argv 是一个 char 数组(字符串)的数组。

请注意,第一个参数始终是你正在运行的程序的路径。


2

你可以在任何教程中参考基本的c++程序。

argc- number of argument count
argv- argumant list

以下是解析参数列表的示例代码。
#include <iomanip>
#include <iostream>
using namespace std;

int main( int argc, char* argv[] )
  {
  cout << "The name used to start the program: " << argv[ 0 ]
       << "\nArguments are:\n";
  for (int n = 1; n < argc; n++)
    cout << setw( 2 ) << n << ": " << argv[ n ] << '\n';
  return 0;
  }

如果您正在使用Visual Studio,可以使用命令行属性来传递命令行参数。请保留HTML标签。

1

示例代码:

// command_line_arguments.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
int main( int argc,      // Number of strings in array argv
          char *argv[],   // Array of command-line argument strings
          char *envp[] )  // Array of environment variable strings
{
    int count;

    // Display each command-line argument.
    cout << "\nCommand-line arguments:\n";
    for( count = 0; count < argc; count++ )
         cout << "  argv[" << count << "]   "
                << argv[count] << "\n";
}

想了解C++中的参数解析,请阅读MSDN中的Parsing C++ Command-Line Arguments。其中也包含输入输出的示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接