Java では、 で引数を渡すことができますvoid main(String[] args)
。
run configuration
Eclipse では検索し、引数を入れてプログラムを実行しますが、C++ ではint main()
Visual Studio 2010 を使用してプログラムに引数を渡す方法しかありません。
Java では、 で引数を渡すことができますvoid main(String[] args)
。
run configuration
Eclipse では検索し、引数を入れてプログラムを実行しますが、C++ ではint main()
Visual Studio 2010 を使用してプログラムに引数を渡す方法しかありません。
int main()
は正しいですが、int main(int argc, char *argv[])
orint main(int argc, char **argv)
を使用して引数の数を取得し、 を使用しargc
て char 配列 (文字列) の配列を取得できますargv
。
最初の引数は常に、実行中のプログラムへのパスになることに注意してください。
これについては、どのチュートリアルでも基本的な 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 を使用している場合は、コマンドライン パラメータを渡すことができるコマンド ライン プロパティがあります。
サンプルコード:
// 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の C++ コマンド ライン引数の解析を参照してください。入出力の例もあります。