Skip to main content

Command Palette

Search for a command to run...

Identifying Character Types

Updated
2 min read
Identifying Character Types

Q.Write a C++ program to accept a character. Print whether the character is an alphabet, digit, or a special character. Display appropriate messages.

#include <iostream>
using namespace std;

int main()
{
    char ch;

    cout<<" Enter a character : ";
    cin>>ch;

    if(isalpha(ch)){

        cout<<" The character "<< ch <<" is an alaphabet "<<endl;

    }
    else if (isdigit(ch)){
        cout<<" The character "<<ch<<" is a digit "<<endl;

    }
    else {
        cout<<" The character "<<ch<<" is a special character "<<endl;

    }
return 0;
}

Output

Enter a character : A
The character A is an alaphabet.

           or
Enter a character : 10.
The character 10 is a digit.

           or
Enter a character : @.
The character @ is a special character.
if (isalpha(ch)) {
    cout << "The character " << ch << " is an alphabet." << endl;
} else if (isdigit(ch)) {
    cout << "The character " << ch << " is a digit." << endl;
} else {
    cout << "The character " << ch << " is a special character." << endl;
}
  • Alphabet Check: The isalpha function checks if the character is an alphabet (either uppercase or lowercase). If true, it prints that the character is an alphabet.

  • Digit Check: The isdigit function checks if the character is a digit (0-9). If true, it prints that the character is a digit.

  • Special Character Check: If the character is neither an alphabet nor a digit, it is identified as a special character, and the program prints the corresponding message.