Gtld Checking Program (is there a more concise solution?)

So the program originally checked if the input was a Gtld ( .com .net .org and .info ) and then put out a yes or no answer. Then I had to modify the code so that someone could input the Gtld's without the . in front and it would still be valid. I solved the problem but I feel like I could shorten up the code and do the same thing...

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
string inputName = "";
string searchName = "";
string coreGtld1 = ".com";
string coreGtld2 = ".net";
string coreGtld3 = ".org";
string coreGtld4 = ".info";
bool isCoreGtld = false;

cout << endl << "Enter a top-level domain name: " << endl;
cin >> inputName;

searchName = inputName;


if ( (inputName.at(0) == 'c')) {
inputName = coreGtld1;
isCoreGtld = true;
}
else if ( (inputName.at(0) == 'n')) {
inputName = coreGtld2;
isCoreGtld = true;
}
else if ((inputName.at(0) == 'o')) {
inputName = coreGtld3;
isCoreGtld = true;
}
else if ((inputName.at(0) == 'i')) {
inputName = coreGtld4;
isCoreGtld = true;
}
else if (searchName == coreGtld1) {
isCoreGtld = true;
}
else if (searchName == coreGtld2) {
isCoreGtld = true;
}
else if (searchName == coreGtld3) {
isCoreGtld = true;
}
else if (searchName == coreGtld4) {
isCoreGtld = true;
}

else {
isCoreGtld = false;
}
cout << "The name \"" << inputName << "\" ";
if (isCoreGtld) {
cout << "is a core gTLD." << endl;
}
else {
cout << "is not a core gTLD." << endl;
}

return 0;
}

Last edited on
Suppose that you have all the valid domains in a container (like a vector). To check for validity you may search that container
1
2
3
4
5
std::find(
	domain.begin(),
	domain.end(),
	input
) not_eq domain.end()


To solve the missing `.' at the start, you may simply add it if it were not present
1
2
if(not input.empty() and input[0] not_eq '.')
	input = '.' + input;

concise (if we remove the comments):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <regex>
#include <string>

int main()
{
    std::cout << "enter a top-level domain name: " ;
    std::string input ;
    std::cin >> input ;

    // ^ - beginning of string
    // \.? - an optional period
    // (?:com|net|org|edu|gov|int|mil)$) one of the seven alternatives (?: don't capture)
    // $ end of string
    const std::regex gtld_re( R"(^\.?(?:com|net|org|edu|gov|int|mil)$)" ) ; // only the seven original gtlds

    // http://en.cppreference.com/w/cpp/regex/regex_match
    const bool is_core_gtld = std::regex_match( input, gtld_re ) ;

    // ..
}
K thanks guys much appreciated !
Topic archived. No new replies allowed.