Write a program which has a class called String containing a character array as a data member. The class should contain constructor for input and an appropriate member function for throwing an exception in case the ASCII value of a character is prime. You may use any other data members or member functions you deem necessary for computing the answer
#include <iostream>
#include <string>
using namespace std;
class String{
private:
//a character array as a data member.
char character[1000];
//This function checks if the number is prime
bool isPrime(int number){
if (number == 0 || number == 1) {
return false;
}else {
for (int i = 2; i <= number / 2; ++i) {
if (number % i == 0) {
return false;
}
}
}
return true;
}
public:
//The class should contain constructor for input
String(char character[]){
strcpy(this->character,character);
}
//throwing an exception in case the ASCII value of a character is prime.
void checkString(){
for (int i = 0; i <strlen(this->character); ++i) {
if(isPrime(int(this->character[i]))){
cout<<"Value is: "<<this->character[i]<<", ASCII value is: "<<int(this->character[i])<<"\n";
throw invalid_argument("The ASCII value of a character is prime");
}
}
}
};
int main(){
//test String class
char inputString[1000];
//get string from the user
cout<<"Enter a string: ";
cin.get(inputString, 1000);
try {
String _string(inputString);
_string.checkString();
}
catch(exception& e ) {
cout<<e.what()<<"\n\n";
}
//delay
system("pause");
return 0;
}
Comments
Leave a comment