2013年10月25日金曜日

開発環境

C実践プログラミング 第3版 (Steve Oualline (著)、 望月 康司 (監訳) (翻訳)、谷口 功 (翻訳)、オライリー・ジャパン)のⅡ部(単純なプログラミング)の9章(変数スコープおよび関数)、9.4(構造かプログラミング)、9.5(再帰)、9.7(プログラミング実習)、実習 9-1を解いてみる。

その他参考書籍

実習 9-1.

コード

sample.c

#include <stdio.h>
#include <string.h>
/*
 *  countWords -- 文字列中の「語」数を数える関数
 *    語: 1文字以上の英数字からなる単語
 *  パラメータ
 *    string -- 文字列
 *  戻り値
 *    「語」数
 */
 int main()
 {
     int countWords(char s[]);
     char line1[100];
     char line2[100];
     char line3[100];
     char line4[100];
     char line5[100];
     strcpy(line1, "Hello, World!");
     strcpy(line2, "");
     strcpy(line3, "a 1");
     strcpy(line4, "  bc\n\t");
     strcpy(line5, "e");
     printf("%s: 語数 %d\n", line1, countWords(line1));
     printf("%s: 語数 %d\n", line2, countWords(line2));
     printf("%s: 語数 %d\n", line3, countWords(line3));
     printf("%s: 語数 %d\n", line4, countWords(line4));
     printf("%s: 語数 %d\n", line5, countWords(line5));
     return (0);
 }
 
 int countWords(char s[])
 {
     int count = 0;
     int i = 0;
     int flag = 0;
     while (s[i] != '\0'){
         if (('A' <= s[i] && s[i] <= 'Z') ||
                 ('a' <= s[i] && s[i] <= 'z') ||
                 ('0' <= s[i] && s[i] <= '9')){
             if (flag == 0){
                 flag = 1;
                 count += 1;
             }
         } else {
             flag = 0;
         }
         i += 1;
     }
     
     return (count);
 }

makefile

CC=cc
CFLAGS=-g

sample: sample.c
 $(CC) $(CFLAGS) -o sample sample.c

clean:
 rm -f sample

入出力結果(Terminal)

$ make
cc -g -o sample sample.c
$ ./sample
Hello, World!: 語数 2
: 語数 0
a 1: 語数 2
  bc
 : 語数 1
e: 語数 1
$

0 コメント:

コメントを投稿