Home »
C++ Programs
C++ program to check if the string contains only alphabets using class
Submitted by Shubh Pachori, on September 06, 2022
Problem statement
Given a string, we have to check if the string contains only alphabets using the class and object approach.
Example:
Input:
Enter String: SHUBH
Output:
String contains only alphabets
C++ code to check if the string contains only alphabets 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);
}
// isAlphabet() function to check if
// the string is in alphabet
void isAlphabet() {
// 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 Alphabet
if ((str[index] >= 'A' && str[index] <= 'Z') ||
(str[index] >= 'a' && str[index] <= 'z') || (str[index] == 32)) {
check++;
} else {
check = 0;
break;
}
}
if (check != 0) {
cout << "String contains only alphabets" << endl;
break;
} else {
cout << "String does not contain only alphabets " << endl;
break;
}
}
}
};
int main() {
// create an object
String S;
// calling getString() function to
// insert string
S.getString();
// calling isAlphabet() function to
// check the string
S.isAlphabet();
return 0;
}
Output
RUN 1:
Enter String: Hello
String contains only alphabets
RUN 2:
Enter String: Hello1
String does not contain only alphabets
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 isAlphabet() to store the string and to check if the string is in the alphabet 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 isAlphabet() member function to check the string if it is in the alphabet or not. The isAlphabet() function contains the logic to check if the string is in the alphabet or not and printing the result.
C++ Class and Object Programs (Set 2) »