Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <cctype> // isdigit()
- #include <vector>
- using namespace std;
- // This function returns true if a string represents a number.
- // Otherwise, it returns false.
- // 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 your_number = ""; // User input from the console is a string.
- float your_number_float = 0.0; // User input converted to a float (has a decimal point).
- vector<float> table; // This is a list of the values for the multiplication table (input times 1 to 12).
- cout << "\n This program will\n"
- " print a multiplication table\n"
- " of your number from 0 - 12\n\n";
- cout << " Enter a number: ";
- getline(cin, your_number); // Store user input. User input from the console comes in as a string, not a number.
- while (!validate_number(your_number)) // Use validation function to make sure the string input is a number (see above).
- {
- cout << " " << your_number << " is not a number.\n";
- cout << " Please enter a number: ";
- getline(cin, your_number); // Get new user input.
- }
- your_number_float = stof(your_number); // Once you know the string number is valid, convert it to an actual number.
- for (int i = 0; i <= 12; ++i)
- table.push_back(your_number_float * i); // Calculate the number times 1 to 12 and store them as a list.
- // Display the results.
- cout << " \n\n---------------------------------\n"; // Begin title.
- cout << " Number " << your_number_float
- << " multiplied by 0 - 12\n\n"; // End of title.
- cout << " " << your_number_float << " x\n" // Begin top of table.
- " ---------------------"
- << '\n'; // End top of table.
- for (int j = 0; j <= 12; ++j) // Diplay each calculation, 1 to 12.
- cout << " " << j << " | "
- << table[j] << '\n' // This is the calcualtion stored on the list.
- << " ------------\n";
- }
Add Comment
Please, Sign In to add comment