<\/span><\/h2>\n\n\n\nYou inherited a piece of code that performs username validation for your company’s website. The existing function works reasonably well, but it throws an exception when the username is too short. Upon review, you realize that nobody ever defined the exception.<\/p>\n\n\n\n
The inherited code is provided for you in the locked section of your editor. Complete the code so that, when an exception is thrown, it prints Too short: n<\/code> (where n<\/em><\/strong> is the length of the given username).<\/p>\n\n\n\n<\/span>Input Format<\/strong><\/span><\/h2>\n\n\n\nThe first line contains an integer, t<\/em><\/strong>, the number of test cases.
Each of the t<\/em><\/strong> subsequent lines describes a test case as a single username string, u<\/em><\/strong>.<\/p>\n\n\n\n<\/span>Constraints<\/strong><\/span><\/h2>\n\n\n\n- 1 <= t <= 1000<\/strong><\/li>
- 1 <= |u<\/em>| <= 100<\/strong><\/li>
- The username consists only of uppercase and lowercase letters.<\/li><\/ul>\n\n\n\n
<\/span>Output Format<\/strong><\/span><\/h2>\n\n\n\nYou are not responsible for directly printing anything to stdout. If your code is correct, the locked stub code in your editor will print either Valid<\/code> (if the username is valid), Invalid<\/code> (if the username is invalid), or Too short: n<\/code> (where n<\/em><\/strong> is the length of the too-short username) on a new line for each test case.<\/p>\n\n\n\nSample Input<\/strong><\/p>\n\n\n\n3\nPeter\nMe\nArxwwz<\/code><\/pre>\n\n\n\nSample Output<\/strong><\/p>\n\n\n\nValid\nToo short: 2\nInvalid<\/code><\/pre>\n\n\n\n<\/span>Explanation<\/strong><\/span><\/h2>\n\n\n\nUsername Me<\/code> is too short because it only contains 2<\/strong> characters, so your exception prints Too short: 2<\/strong>.
All other validation is handled by the locked code in your editor.<\/p>\n\n\n\n<\/span>Solution – Inherited Code in C++<\/strong><\/span><\/h2>\n\n\n\n<\/span>C++<\/strong><\/span><\/h3>\n\n\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <exception>\nusing namespace std;\n\n\/* Define the exception here *\/\nclass BadLengthException {\n private: \n int n;\n public:\n BadLengthException(int errornumber) {\n n = errornumber;\n }\n \n int what() {return n;}\n};\n\n\nbool checkUsername(string username) {\n\tbool isValid = true;\n\tint n = username.length();\n\tif(n < 5) {\n\t\tthrow BadLengthException(n);\n\t}\n\tfor(int i = 0; i < n-1; i++) {\n\t\tif(username[i] == 'w' && username[i+1] == 'w') {\n\t\t\tisValid = false;\n\t\t}\n\t}\n\treturn isValid;\n}\n\nint main() {\n\tint T; cin >> T;\n\twhile(T--) {\n\t\tstring username;\n\t\tcin >> username;\n\t\ttry {\n\t\t\tbool isValid = checkUsername(username);\n\t\t\tif(isValid) {\n\t\t\t\tcout << \"Valid\" << '\\n';\n\t\t\t} else {\n\t\t\t\tcout << \"Invalid\" << '\\n';\n\t\t\t}\n\t\t} catch (BadLengthException e) {\n\t\t\tcout << \"Too short: \" << e.what() << '\\n';\n\t\t}\n\t}\n\treturn 0;\n}<\/pre>\n\n\n\n