C++ isalpha()

The isalpha() function in C++ checks if the given character is an alphabet or not. It is defined in the cctype header file.

Example

#include <iostream>
#include <cctype>
using namespace std;

int main() {

// check if '7' is an alphabet int result = isalpha('7');
cout << result; return 0; } // Output: 0

isalpha() Syntax

The syntax of isalpha() is:

isalpha(int ch);

Here, ch is the character that we want to check.


isalpha() Parameters

The isalpha() function takes the following parameter:

  • ch - the character to check, casted to int or EOF

isalpha() Return Value

The isalpha() function returns:

  • non-zero value if ch is an alphabet
  • zero if ch is not an alphabet

isalpha() Prototype

The prototype of isalpha() as defined in the cctype header file is:

int isalpha(int ch);

Here, ch is checked for alphabets as classified by the currently installed C locale. By default, the following characters are alphabets:

  • Uppercase Letters: 'A' to 'Z'
  • Lowercase Letters: 'a' to 'z'

isalpha() Undefined Behavior

The behaviour of isalpha() is undefined if:

  • the value of ch is not representable as unsigned char, or
  • the value of ch is not equal to EOF

Example: C++ isalpha()

#include <cctype>
#include <iostream>
#include <cstring>

using namespace std;

int main() {
  char str[] = "ad138kw+~!$%?';]qjj";
  int count = 0, check;

  // loop to count the no. of alphabets in str
  for (int i = 0; i <= strlen(str); ++i) {

// check if str[i] is an alphabet check = isalpha(str[i]);
// increment count if str[i] is an alphabet if (check) ++count; } cout << "Number of alphabet characters: " << count << endl; cout << "Number of non-alphabet characters: " << strlen(str) - count; return 0; }

Output

Number of alphabet characters: 7
Number of non alphabet characters: 12

In this program, we have used a for loop and the isalpha() function to count the number of alphabets in str.

The following variables and codes are used in this program:

  • strlen(str) - gives the length of the str string
  • check - checks if str[i] is an alphabet with the help of isalpha()
  • count - stores the number of alphabets in str
  • strlen(str) - count - gives the number of non-alphabets in str
Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community