C++ program to define exception for small username, and validate username

C++Server Side ProgrammingProgramming

Suppose we have a string of usernames and we shall have to check whether username is valid or not based on few conditions. So we shall have to define an exception that is thrown when the length of username is less than 5 characters long. We shall have to return "Valid" for valid username, "Invalid" for invalid username and throw exception for smaller usernames. The valid username conditions are −

  • Username must be five-character long

  • There should not two consecutive 'w' in the username

So, if the input is like unames = ["amit", "to", "paul_tim", "greg_harry", "towwer"], then the output will be [Too short: 4, Too short: 2, Valid, Valid, Invalid] because first two is too small, and last one has two consecutive 'w's. Others are fine.

To solve this, we will follow these steps −

  • Define an exception called BadLengthExcaption

  • it will return message the length

  • Define a function validation(), this will take u_name,

  • isValid := true

  • n := size of u_name

  • if n < 5, then:

    • throw an BadLengthException(n)

  • for initialize i := 0, when i < n-1, update (increase i by 1), do:

    • if u_name[i] is same as 'w' and u_name[i + 1] is same as 'w', then:

      • isValid := false

  • return isValid

  • From the main method do the following:

  • for all username u_name in unames, do

    • validate(u_name)

    • if valid print VALID

    • otherwise when invalid print INVALID

    • otherwise when length is small print Too Small

Example

Let us see the following implementation to get better understanding −

#include <iostream>
#include <vector>
#include <exception>
using namespace std;
class BadLengthException{
    public:
    int x;
    BadLengthException(int n) {
        x=n;
    }
    int what() const throw(){return x;}
};
bool validation(string u_name) {
    bool isValid = true;
    int n = u_name.length();
    if(n < 5) {
        throw BadLengthException(n);
    }
    for(int i = 0; i < n-1; i++) {
        if(u_name[i] == 'w' && u_name[i+1] == 'w') {
            isValid = false;
        }
    }
    return isValid;
}
int main() {
    vector<string> unames = {"amit", "to", "paul_tim", "greg_harry", "towwer"};
    for(int i = 0; i < unames.size(); i++){
        string u_name = unames[i];
        try {
            bool isValid = validation(u_name);
            if(isValid) {
                cout << "Valid" << '\n';
            } else {
                cout << "Invalid" << '\n';
            }
        } catch (BadLengthException e) {
            cout << "Too short: " << e.what() << '\n';
        }
    }
}

Input

{"amit", "to", "paul_tim", "greg_harry", "towwer"}

Output

Too short: 4
Too short: 2
Valid
Valid
Invalid
raja
Published on 07-Oct-2021 08:40:06
Advertisements