isalpha() 함수란?
isalpha() 함수는 전달된 문자가 알파벳(영문자)인지 아닌지를 검사하는 데 사용됩니다. 이 함수는 <ctype.h> 헤더 파일에 선언되어 있으며, 인수로 전달된 문자가 알파벳이면 0이 아닌 정수 값(참)을 반환하고, 그렇지 않으면 0(거짓)을 반환합니다.
C 언어에서 isalpha() 함수의 문법은 다음과 같습니다.
int isalpha(int value);
매개변수 설명
- value − 검사할 문자를 나타내는 정수형(int) 단일 인수입니다.
isalpha() 예제 코드
#include<stdio.h>
#include<ctype.h>
int main() {
char val1 = 's';
char val2 = '8';
if(isalpha(val1))
printf("The character is an alphabet\n");
else
printf("The character is not an alphabet\n");
if(isalpha(val2))
printf("The character is an alphabet\n");
else
printf("The character is not an alphabet");
return 0;
}실행 결과
The character is an alphabet The character is not an alphabet
위 예제에서 변수 val1에는 문자 's'가 저장되어 있으므로 isalpha()가 참을 반환해 "알파벳입니다"라는 메시지가 출력되고, val2에는 숫자 문자 '8'이 저장되어 있어 거짓을 반환합니다.
isdigit() 함수란?
isdigit() 함수는 전달된 문자가 숫자(0~9)인지 아닌지를 검사하는 데 사용됩니다. 마찬가지로 <ctype.h> 헤더 파일에 선언되어 있으며, 인수가 숫자 문자이면 0이 아닌 정수 값을 반환하고, 그렇지 않으면 0을 반환합니다.
C 언어에서 isdigit() 함수의 문법은 다음과 같습니다.
int isdigit(int value);
매개변수 설명
- value − 검사할 문자를 나타내는 정수형(int) 단일 인수입니다.
isdigit() 예제 코드
#include<stdio.h>
#include<ctype.h>
int main() {
char val1 = 's';
char val2 = '8';
if(isdigit(val1))
printf("The character is a digit\n");
else
printf("The character is not a digit\n");
if(isdigit(val2))
printf("The character is a digit\n");
else
printf("The character is not a digit");
return 0;
}실행 결과
The character is not a digit The character is a digit
문자 's'는 숫자가 아니므로 첫 번째 조건문은 거짓이 되고, 문자 '8'은 숫자이므로 두 번째 조건문은 참이 됩니다.
isalpha()와 isdigit()의 차이점 정리
| 함수 | 검사 대상 | 반환값 (참일 때) |
|---|---|---|
| isalpha() | 영문 알파벳(A~Z, a~z) | 0이 아닌 값 |
| isdigit() | 숫자 문자(0~9) | 0이 아닌 값 |
두 함수 모두 사용자 입력 검증, 문자열 파싱 등에서 매우 유용하게 활용되며, C++에서도 <cctype> 헤더를 통해 동일하게 사용할 수 있습니다.