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

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

Example:

Input:
Enter String: Shubh

Output:
String is not in uppercase!

C++ code to check if the string is in uppercase 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);
  }

  // isUppercase() function to check if 
  // the string is in uppercase
  void isUppercase() {
    // 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 if the character 
      // at index is alphabet or not
      if ((str[index] >= 'A' && str[index] <= 'Z') ||
          (str[index] >= 'a' && str[index] <= 'z') || (str[index] == 32)) {
        // if condition to check if the character 
        // at index is in uppercase or not
        if ((str[index] >= 'A' && str[index] <= 'Z') || (str[index] == 32)) {
          check++;
        } else {
          check = 0;
          break;
        }
      } else {
        check = 0;
        break;
      }
    }

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

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

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

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

  return 0;
}

Output:

RUN 1:
Enter String: HELLO
String is in uppercase!

RUN 2:
Enter String: Hello
String is not in uppercase!

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 isUppercase() to store the string and to check if the string is in uppercase 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 isUppercase() member function to check the string if it is in uppercase or not. The isUppercase() function contains the logic to check if the string is in uppercase 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.