C++ program to check if all characters of a string are alphanumeric or not

Published by admin on

C++ program to check if all characters are alphanumeric

C++ isalnum() function :

In this tutorial, we will learn how to check if a character is alphanumeric or not in C++. Our program will ask the user to enter one string. It will scan through the characters of the string one by one and print out the non-alphanumeric characters.

In C++, all character handling functions are defined in the cctype header file. It includes one function called isalnum to check for alphanumeric characters. In our program, we will use this function.

 

isalnum function definition :

isalnum is defined as below :

int isalnum(int c);

 

Parameters and return values :

It takes one character to check for alphanumeric. Internally, isalnum converts the character to integer and checks if it is alphanumeric or not.

It returns one integer. zero to indicate false and any other integer to indicate true.

 

C++ program to find non alphanumeric characters :

#include <iostream>
using namespace std;

int main()
{
    //1
    char str[100];

    //2
    cout << "Enter a string to test :" << endl;
    cin.get(str, 100);

    //3
    for (int i = 0; str[i] != '\0'; i++)
    {
        //4
        if (!isalnum(str[i]))
        {
            cout << str[i] << " is not alphanumeric" << endl;
        }
    }
}

 

Explanation :

The commented numbers in the above program denote the step numbers below :

  1. Create one character array of size 100 to store the user-input string.
  2. Ask the user to enter a string. Read and store it in the character array str using cin.
  3. Using one for loop, iterate through the characters of the string one by one. This loop will iterate till a ‘\0’ is found in the array.
  4. Check if the current character is alphanumeric or not. If it is not alphanumeric, print out the result.

 

Sample Output :

Enter a string to test :
hello 99*
  is not alphanumeric
* is not alphanumeric

Enter a string to test :
hello world 898898 &
  is not alphanumeric
  is not alphanumeric
  is not alphanumeric
& is not alphanumeric

Enter a string to test :
he&&**^%$#@qwe!)(+_
& is not alphanumeric
& is not alphanumeric
* is not alphanumeric
* is not alphanumeric
^ is not alphanumeric
% is not alphanumeric
$ is not alphanumeric
# is not alphanumeric
@ is not alphanumeric
! is not alphanumeric
) is not alphanumeric
( is not alphanumeric
+ is not alphanumeric
_ is not alphanumeric

C++ check alphanumeric characters

 

Conclusion :

isalnum() makes it easy to check if a character is alphanumeric or not. This function is also defined in the header . This is a local specific version.

Categories: C++

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *