next up previous
Next: 4 if文について Up: c_lang Previous: 2 変数の型の定義について

Subsections


3 キーボードからの入力方法

それでは、キーボードから入力した文字列や値を返すプログラムを練習します。 早速、以下のプログラムを入力し実行してみてください。一番左側の数字は''行 数''を表わしており、入力しないでください。
---------- Program ----------------------
1:  #include <stdio.h>
2: 
3:  int main(void);
4: 
5:  int main(void)
6:  {
7:    char  a[50], b[3];      <== 文字列型の定義
8:    int   c;
9:
10:    printf("What's your name?\n");
11:    gets(a);
12:    printf("Hello, Mr. or Ms. %s! \nHow old are you ?\n",a);
13:    gets(b);
14:    printf("Age of %s is an almost adult.  You  are not a child.\n", b);
15:    c = atoi(b);
16:    printf("After graduating, you supposed to  
          be  %d or %d years old.\n", c + 4, c + 5 );  <== 一行で続けて書く 
17:
18:  }
----------- Program END -----------------

コンパイルの時に"warning"が表示されるかも知れません。
"error"でなけれれば、ここでは気にしなくて結構です。
以下、実行結果です。 
 
---------- 実行結果 ----------------------
[nisimiya@dhcp32 C_Exercise]$ ./ex713_9
What's your name?
Nobuo Nishimiya
Hello, Mr. or Ms. Nobuo Nishimiya! 
How old are you ?
19
Age of 19 is an almost adult.  You  are not a child.
After graduating, you supposed to  be  23 or 24 years old.
---------- 実行結果 ここまで -------------

プログラムの意味を解説します。 7行目の''char a[50]''と言うのは、「文字列型」変数です。``char''は ``charcter''の事です。 文字列には長さが必要です。 ``[50]''というのは、``長さ50文字までの変数''を表わします。 もし、あなたの氏名が50文字で入りきらない場合は、このままではエラーになり ます。 もう少し増やしてください。 (実際には、一行分という意味で、256に設定することが多いようです。) 年齢はガンダルフ(111歳?)でも3文字あれば良いでしょう。

11行目の ``gets(a)''と言うのが、キーボード入力を表わします。入力した文字 列は、文字変数``a''に代入されます。

15行目は何か? ``c=atoi(b)''というのは、文字列変数 ``b''を整数変数に変換後、``c''に代入し ているところです。 人間にとっては ``19''と表示されても、整数なのか文字列なのか判断できませ んが、コンピュータは判断しています。もしこの型変換を行わないと、 16行目の ``c+4''でエラーになります。 16行目では``c''を整数として計算してます。

3.1 演習

キーボードから数値を2回入力し、その和,差,積を計算し表示するプログラ ムを作成せよ。
実行例は、以下の通り。

---------- 実行例 ----------------------
[nisimiya@dhcp32 C_Exercise]$ ./ex713_11
Please input first number?
5
The first number is 5

Please input second number?
2
The second number is 2

1st  plus  2nd equals  7.000000
1st  minus 2nd equals  3.000000
1st  times 2nd equals  10.000000
1st  devided by 2nd equals  2.500000
---------- 実行例ここまで -------------



Nobuo Nishimiya
平成21年6月23日