Currently, your check that if (date[5] < 1 || date[5] > 2)
is not exactly what you intend. Most C++ (and C) compilers encode its characters following ASCII. So the character '0'
(often) has an integer value of 48
, the character '1'
(often) has an integer value of 49
and so on.
Another issue with your current code is with the recursion. The following piece of code will loop, print output, and recurse indefinitely. (Even if the next date entry is valid, it will continue looping.)
while(date.length() > 9 || date.length() < 9)
{
cout << "\nInvalid entry, must be 9 characters.\n";
getDate();
}
You can simply use an if
-statement here... and remember to handle your recursion properly. (i.e. You want to make sure that the result of the new getDate()
is returned. Thus, return getDate();
)
Rather than using a barrage of if
-statements, I'd recommend converting the string to a number first before checking whether or not it is within the range 1900
to 2100
.
string getDate()
{
std::string date = "01APR2021"; // read date (or hard-code it)
// perform checks
if (date.length() != 9) // you can simplify your length check
{
// error message
return getDate(); // beware of your while-loop and recursion
}
std::string lastFour(date.end() - 4, date.end()); // substring of last four characters of date
std::string::size_type noIntTrack; // tracks the stoi finishing position
int year = std::stoi(lastFour, &noIntTrack); // converts the year to an integer
if (noIntTrack != 4) // if not 4 => unsuccessful conversion
{ // e.g. maybe user entered 01APR20AA
// error handling:
// noIntTrack should be 4 to signify successful conversion of all characters
return getDate(); // recurse
}
if (!(1990 <= year && year <= 2100)) // check if year not in range
{
// handle year out of range
return getDate();
}
// other checks (e.g. month/date?)
// if (date is not good) { return getDate(); }
// date is valid:
// party
return date;
}