#include #include #include using namespace std; // Determine if a string represents a number. // There can be one decimal point. There can be a plus or minus sign, if followed by a digit. // All characters other than . + - must be a digit. bool validate_number(string number) { int num_decimal_points = 0; // Count decimal points. There can only be one. for (size_t i = 0; i < number.length(); ++i) // Check each character. { if (number[i] == '.') // If it's a decimal point, { ++num_decimal_points; // Count it. } else if ( (number[i] == '+') || (number[i] == '-') ) // If it's + or - { if (!isdigit(number[i + 1])) // If the next character is not a digit, { return false; // This number is invalid. } } else if ( !isdigit(number[i]) ) // Else if it's not a digit, { return false; // This number is invalid. } } if (num_decimal_points > 1) // If there's more than one decimal point, { return false; // This number is invalid. } // If there's a decimal point but no digits, if ((num_decimal_points == 1) && (number.length() == 1)) { return false; // This number is invalid. } return true; // The number is valid. } int main() { string number; // A string that may represent a number. cout << "Enter a number:\n"; cin >> number; // Get the string. // If the string represents a number, if (validate_number(number)) { cout << "It's a number.\n"; } else // If the string doesn't represent a number, { cout << "It's not a valid number.\n"; } }