After spending a lot of time studying input validation, I combined several ideas and came up with the following:
String check function for a valid double ...
bool isDouble(double& destination, string& source) { // 64 bit bool goodValue = false; if (!source.empty()) { errno = 0; char *garbage = nullptr; destination = strtod(source.c_str(), &garbage); if (*garbage == '\0' && errno != ERANGE) goodValue = true; } return goodValue; }
String check function for a valid 32-bit integer ...
bool isLong(long& destination, string& source) { // 32 bit (base 10) const short BASE = 10; bool goodValue = false; if (!source.empty()) { errno = 0; char* garbage = nullptr; destination = strtol(source.c_str(), &garbage, BASE); if (*garbage == '\0' && errno != ERANGE) goodValue = true; } return goodValue; }
Implementation example
using namespace std; int main() { string buffer; double value; cout << "Enter a value: "; getline(cin, buffer, '\n'); if (isDouble(value, buffer)) cout << "Value: " << value << endl; else cout << "ERROR: Invalid input\n"; return 0; }
Can anyone comment if I miss something with this approach?
c ++ floating-point input validation
user898058
source share