とらりもんHOME  Index  Search  Changes  Login

とらりもん - C intro 7. argument Diff

  • Added parts are displayed like this.
  • Deleted parts are displayed like this.

To give some information to a program, you can do it from the command line as well as standard input. As an example, consider the following program:

    /* add2.c
     * usage (example): $ ./add2 1.2 3.6
     * compile: $ gcc add2.c -o add2
     * 2018/07/16 K. Nasahara
     */
    # include <stdio.h>
    # include <stdlib.h>
    main(int argc, char **argv)
    {float x, y;
     x=atof(argv[1]);
     y=atof(argv[2]);
     printf("%f + %f = %f\n", x, y, x+y);
    }

Now let's compile and run:

$ gcc add2.c -o add2
$ ./add2 1.2 3.6
1.200000 + 3.600000 = 4.800000

This is a program to answer the sum of two numbers. We have made similar program before, but this is a little different. This program takes two numbers {{fontc("in the command line", red)}} at the same time of starting the program, whereas the program we made last time took numbers from standard input (after starting the program). This style is suitable for controlling parameters in the program and used frequently. The data given to the program in this style (on the command line) are called {{fontc("arguments", red)}}.

Let's see the detail. First, we replaced usual "main()" by "main(int argc, char **argv)". "argc" and "argv" are conventional words which are used in such case. "argc" automatically takes a value of numbers the arguments. "argv" is "a pointer to a pointer". We skip the details about it here. In short, argv[0] describes the command name, argv[1] describes the first argument, argv[2] describes the second argument, and so on.

 さて、"1.2"という引数は、プログラムに渡された時点では、文字列として認識されている。これを、実数として認識しなおすために、Note that the arguments are described in strings (array of characters). Therefore, "1.2" is not recognized as a number but a word or a sentence. The line
x=atof(argv[1]);という関数を実行している。このatofという関数は、文字列として表現された実数を、実数として認識するものである。また、この関数を使うために、プログラムの最初の方で、stdlib.hというライブラリを使うことを宣言している。ちなみに、文字列を整数として認識する関数はatoiである。
converts this "word" to a real number. This "atof" function needs to be defined at the beginning of the program, which is done by "#include stdlib.h" at the head of the program. For your interest, you use "atoi" instead of "atof" if you want to convert a word to an integer.


----
''課題1'': コマンドラインから正の整数nの値を得て、1からnまでの和を計算するプログラムを作れ。

<[[C言語入門]]に戻る>

''Exercise 7-1'': Get a number in the command line and calculate sum of the integers from 1 to that number.

[Go back to [[C language introduction]]]