コマンドライン引数

/*test.c*/
#include <stdio.h>
int main(int argc, char *argv[])
{
       int i;
       for (i = 0; i < argc; i++)
              printf("argv[%d] = %s\n", i, argv[i]);

       return 0;
}
    • 実行時にシェルから値を入れることができて
./test a b c 1 2 3
    • 実行結果
~$ ./test a b c 1 2 3
argv[0] = ./test
argv[1] = a
argv[2] = b
argv[3] = c
argv[4] = 1
argv[5] = 2
argv[6] = 3
    • 今の場合 argc は 7
    • argv[0] がファイル名で その後に順番に値が代入される
  • 数値への変換
  • まずstdlib.hをインクルード
#include <stdlib.h>
    • 文字から整数
int atoi(const char *s);
double atof(const char *s);
  • こんなかんじでとりあえず動いた
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
	int i;
	for (i = 0; i < argc; i++)
		printf("argv[%d] = %s\n", i, argv[i]);
	double x,y,z;
	x = atof(argv[1]);
	y = atof(argv[2]);
	z = x/y;
	printf("%f\n",z);
	
	return 0;
}