以下にこららの関数の使用例を示す。
#include <ctype.h> /* ctype.hをインクルード */
#include <stdio.h>
void
check_char(char c)
{
printf("check '%c'¥n", c);
if (isalpha(c)) { /* アルファベットかどうか */
printf("'%c' is alphabet¥n", c);
}
if (isdigit(c)) { /* 数字かどうか */
printf("'%c' is digit char¥n", c);
}
if (isupper(c)) { /* 大文字かどうか */
printf("'%c' is uppercase char¥n", c);
printf("lowercase of '%c' is '%c'¥n", c, tolower(c));
}
if (islower(c)) { /* 小文字かどうか */
printf("'%c' is lowercase char¥n", c);
printf("uppercase of '%c' is '%c'¥n", c, toupper(c));
}
if (isspace(c)) { /* 空白文字かどうか */
printf("'%c' is white space¥n", c);
}
printf("¥n");
}
int
main(void)
{
int c;
printf("input character=");
c = getchar(); /* 1文字入力 */
check_char(c); /* 入力した文字をチェック */
return 0;
}
上記のサンプルプログラムを実行すると以下の出力結果となる。
(斜字体部分はユーザの入力)
('a'を入力した場合)
input character=a
check 'a'
'a' is alphabet
'a' is lowercase char
uppercase of 'a' is 'A'
('B'を入力した場合)
input character=B
check 'B'
'B' is alphabet
'B' is uppercase char
lowercase of 'B' is 'b'
('7'を入力した場合)
input character=7
check '7'
'7' is digit char
(' '(スペース)を入力した場合)
input character=
check ' '
' ' is white space
以下の
サンプルコードは入力した文字を大文字にして出力するプログラムである。
入力した文字をint型の変数cに格納している。
これは上で説明した通り、EOFを区別するためである。
#include <stdio.h>
#include <ctype.h>
int
main(void)
{
int c;
while ((c = getchar()) != EOF) /* 入力が終わるまで1文字ずつ入力 */
putchar(toupper(c)); /* 大文字にして出力 */
return 0;
}
上記のサンプルプログラムを実行すると以下の出力結果となる。a quick brown fox jumps over the lazy dog. A QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
上記のサンプルコードで変数 cの型を int型から char型にすると
入力文字がなくなっても変数 cの値が EOFにならなくなるため、
whileループが終了せず、プログラム止まらなくなる。