프로그래밍/C++ 문법

C++에서 isdigit, isalpha 함수 알아보기

studylida 2023. 1. 13. 21:00

1. isdigit

<cctype>에 의해 정의되어 있으며, 매개변수로 들어온 문자가 십진수인지 아닌지 검사하는 함수이다. 매개변수는 검사되어야 하는 문자인 c가 있다. 이를 통해 isdigit 함수는 매개변수로 들어온 c가 십진수인지 아닌지 검사하는 함수라는 것을 알 수 있다. 이때 c는 int나 EOF로 캐스팅된다. 만약 c가 십진수라면 0이 아닌 수를 반환하고(참), c가 십진수가 아니라면 0을 반환한다(거짓). 

 

사용 예시

/* isdigit example */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
{
  char str[]="1776ad";
  int year;
  if (isdigit(str[0]))
  {
    year = atoi (str);
    printf ("The year that followed %d was %d.\n",year,year+1); // 1776, 1777
  }
  return 0;
}

2. std::isdigit

<locale>에 의해 정의되어 있으며, 매개변수로 들어온 로케일 loc의 ctype facet을 사용하여 c가 십진수인지 아닌지 확인한다. 만약 c가 십진수라면 true를 반환하고, 아니라면 false를 반환한다. 이 함수 템플릿은 <cctype>에 정의된 C 함수 isdigit를 오버로드한다.

 

사용 예시

// isdigit example (C++)
#include <iostream>       // std::cout
#include <string>         // std::string
#include <locale>         // std::locale, std::isdigit
#include <sstream>        // std::stringstream

int main ()
{
  std::locale loc;
  std::string str="1776ad";
  if (isdigit(str[0],loc))
  {
    int year;
    std::stringstream(str) >> year;
    std::cout << "The year that followed " << year << " was " << (year+1) << ".\n";
  }
  return 0;
}

 

3. isalpha

<cctype>에 의해 정의되어 있으며, 매개변수로 들어온 문자가 알파벳 문자인지 아닌지 검사하는 함수이다. 매개변수는 검사되어야 하는 문자인 c가 있다. 이를 통해 isalpha 함수는 매개변수로 들어온 c가 알파벳 문자인지 아닌지 검사하는 함수라는 것을 알 수 있다. 만약 c가 알파벳 문자가 맞다면 0이 아닌 수를 반환하고(참), 아니라면 0을 반환한다(거짓). Visual Studio에서는 소문자를 넣으면 2, 대문자를 넣으면 1, 알파벳이 아닌 문자를 넣으면 0을 반환한다. 

 

주의사항

사용되는 로케일에 따라 알파벳 문자로 간주되는 것이 달라질 수 있습니다. 

 

사용 예시

/* isalpha example */
#include <stdio.h>
#include <ctype.h>
int main ()
{
  int i=0;
  char str[]="C++";
  while (str[i])
  {
    if (isalpha(str[i])) printf ("character %c is alphabetic\n",str[i]);
    else printf ("character %c is not alphabetic\n",str[i]);
    i++;
  }
  return 0;
}

4. std::isalpha

<locale>에 의해 정의되어 있으며, 매개변수로 들어온 loc를 로케일의 ctype facet을 사용하여 c가 알파벳 문자인지 아닌지 확인한다. 만약 c가 알파벳 문자라면 true를 반환하고, 아니라면 false를 반환한다. 이 함수 템플릿은 에 정의된 C 함수 isalpha를 오버로드한다.

 

사용 예시

// isalpha example (C++)
#include <iostream>       // std::cout
#include <string>         // std::string
#include <locale>         // std::locale, std::isalpha

int main ()
{
  std::locale loc;
  std::string str="C++";

  for (std::string::iterator it=str.begin(); it!=str.end(); ++it)
  {
    if (std::isalpha(*it,loc))
      std::cout << "character " << *it << " is alphabetic\n";
    else
      std::cout << "character " << *it << " is not alphabetic\n";
  }
  return 0;
}

 

관련된 글

 

참고문헌