×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

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

Submitted by Shubh Pachori, on September 06, 2022

Problem statement

Given a string, we have to check if the string is in numeric using the class and object approach.

Example:

Input:
Enter String: 12345

Output:
String is in numeric!

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

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

    // for loop to traverse the whole string
    for (index = 0; str[index]; index++) {
      // for loop to traverse the whole string
      for (index = 0; str[index]; index++) {
        // if condition to check if the string
        // is in numeric
        if (str[index] >= '0' && str[index] <= '9') {
          check++;
        } else {
          check = 0;
          break;
        }
      }

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

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

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

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

  return 0;
}

Output

RUN 1:
Enter String: 12345
String is in numeric!

RUN 2:
Enter String: Hello12
String is not in numeric!

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