C++ program to check if the string is in alphanumeric using class

Given a string, we have to check if the string is in alphanumeric using the class and object approach.
Submitted by Shubh Pachori, on September 06, 2022

Example:

Input:
Enter String: SHUBH123

Output:
String is in alphanumeric!

C++ code to check if the string is in alphanumeric using the class and object approach

#include <iostream>
using namespace std;

// create a class
class String {
  // private data member
 private:
  char str[30];

  // public member functions
 public:
  // getString() function to 
  // store string
  void getString() {
    cout << "Enter String:";
    cin.getline(str, 30);
  }

  // isAlphanumeric() function to check 
  // if the string is in alphanumeric
  void isAlphanumeric() {
    // initializing int type variables to 
    // perform operations
    int index, check = 0;

    // for loop to traverse the whole string
    for (index = 0; str[index]; index++) {
      // if condition to check for alphabet and 
      // numericals in the string
      if ((str[index] >= 'A' && str[index] <= 'Z') ||
          (str[index] >= 'a' && str[index] <= 'z') || (str[index] == 32) ||
          (str[index] >= '0' && str[index] <= '9')) {
        check++;
      } else {
        check = 0;
        break;
      }
    }

    if (check != 0) {
      cout << "String is in alphanumeric!" << endl;
    } else {
      cout << "String is not in alphanumeric!" << endl;
    }
  }
};

int main() {
  // create an object
  String S;

  // calling getString() function 
  // to insert string
  S.getString();

  // calling isAlphanumeric() function 
  // to check the string
  S.isAlphanumeric();

  return 0;
}

Output:

RUN 1:
Enter String:Abc@123
String is not in alphanumeric!

RUN 2:
Enter String:123@
String is not in alphanumeric!

Explanation:

In the above code, we have created a class String, one char type array data member str[30] to store the string, and public member functions getString() and isAlphanumeric() to store the string and to check if the string is in alphanumeric or not.

In the main() function, we are creating an object S of class String, reading a string by the user using the function getString(), and finally calling the isAlphanumeric() member function to check the string if it is in alphanumeric or not. The isAlphanumeric() function contains the logic to check if the string is alphanumeric or not and printing the result.

C++ Class and Object Programs (Set 2) »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.