Advertisement
janac

Determine if a string represents a number

Nov 26th, 2021
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <cctype>
  4.  
  5. using namespace std;
  6.  
  7. // Determine if a string represents a number.
  8. // There can be one decimal point. There can be a plus or minus sign, if followed by a digit.
  9. // All characters other than . + - must be a digit.
  10. bool validate_number(string number)
  11. {
  12.     int num_decimal_points = 0; // Count decimal points. There can only be one.
  13.     for (size_t i = 0; i < number.length(); ++i) // Check each character.
  14.     {
  15.         if (number[i] == '.') // If it's a decimal point,
  16.         {
  17.             ++num_decimal_points; // Count it.
  18.         }
  19.         else if ( (number[i] == '+') || (number[i] == '-') ) // If it's + or -
  20.         {
  21.             if (!isdigit(number[i + 1])) // If the next character is not a digit,
  22.             {
  23.                 return false; // This number is invalid.
  24.             }
  25.         }
  26.         else if ( !isdigit(number[i]) ) // Else if it's not a digit,
  27.         {
  28.             return false; // This number is invalid.
  29.         }
  30.     }
  31.     if (num_decimal_points > 1) // If there's more than one decimal point,
  32.     {
  33.         return false; // This number is invalid.
  34.     }
  35.     // If there's a decimal point but no digits,
  36.     if ((num_decimal_points == 1) && (number.length() == 1))
  37.     {
  38.         return false; // This number is invalid.
  39.     }
  40.  
  41.     return true; // The number is valid.
  42. }
  43.  
  44. int main()
  45. {
  46.     string number; // A string that may represent a number.
  47.  
  48.     cout << "Enter a number:\n";
  49.     cin >> number; // Get the string.
  50.  
  51.      // If the string represents a number,
  52.     if (validate_number(number))
  53.     {
  54.         cout << "It's a number.\n";
  55.     }
  56.     else // If the string doesn't represent a number,
  57.     {
  58.         cout << "It's not a valid number.\n";
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement