Code for that much might look something like this:
#include <ctype>
#include <string>
#include <iostream>
bool isValidDouble(std::string const &input) {
unsigned pos = 0;
unsigned digits = 0;
bool exponent = false;
while (std::isspace(input[pos])) {
pos++;
}
if (input[pos] == '-' || input[pos]=='+') {
pos++;
}
while (isdigit(input[pos])) {
digits++;
pos++;
}
if (input[pos] == '.') {
pos++;
}
while (std::isdigit(input[pos])) {
digits++;
pos++;
}
if (digits == 0) {
return false;
}
if (input[pos] == 'e' || input[pos] == 'E') {
if (digits == 0) {
return false;
}
exponent = true;
pos++;
}
if (exponent && input[pos] == '-' || input[pos] == '+') {
pos++;
}
while (exponent && std::isdigit(input[pos])) {
pos++;
}
return pos == input.length();
}
int main() {
std::string goodInputs[] = {
" 1234",
" 1.2",
"\t0e2",
"0.1e2",
"1.",
".1",
};
std::string badInputs[] = {
"e2",
".",
""
};
for (auto const &test : goodInputs) {
if (!isValidDouble(test)) {
std::cout << "Test failed for :" << test << "\n";
}
}
for (auto const &test : badInputs) {
if (isValidDouble(test)) {
std::cout << "Test failed for : " << test << "\n";
}
}
}
I'm not entirely sure I understand what other validation you want, so I'll leave it at that for now.