空白、タブ、改行を数える
K&R本 演習1-8
空白、タブ、改行を数えるプログラムを書け
#include <stdio.h> int main (void) { int c; int count = 0; FILE *fp; if ( (fp = fopen("test.txt","r")) == NULL ) { puts("file open error"); return 1; } while( (c = fgetc(fp)) != EOF ) { switch(c){ case '\n': case '\t': case ' ': count++; } } printf("%d count",count); return 0; }
できた。またこうゆう場合はctype.hのisspace関数が使えそう。
#include <stdio.h> #include <ctype.h> int main (void) { int c; int count = 0; FILE *fp; if ( (fp = fopen("test.txt","r")) == NULL ) { puts("file open error"); return 1; } while( (c = fgetc(fp)) != EOF ) { if ( isspace(c) ) { count++; } } printf("%d count",count); return 0; }