Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // References to other code that I can use here
- #include "stdafx.h"
- #include <iostream>
- #include <string>
- using namespace std; // So I don't have to keep typing std:: before everything
- bool is_digits(const string &str) // A boolean true or false function I create, with the parameter of a string (text)
- {
- // Does the string only contain characters the teacher wants?
- return str.find_first_not_of("0123456789") == string::npos; // If so, return true. Otherwise return false
- }
- int _tmain(int argc, _TCHAR* argv[]) // This function/method gets run as soon as the program starts
- {
- string sNums; // Variable to hold the string they enter
- bool isValid; // Whether or not the string they've entered is a valid positive integer
- do { // Do the following code until the condition next to (while) is false
- cout << "Enter a positive integer: "; // Ask for a string (text) from the user
- getline(cin, sNums); // Get the string and store it into our variable (sNums)
- cout << endl; // Display everything after this on a new line
- isValid = sNums.length() && is_digits(sNums); // Set our boolean (true or false) variable to the result (return value) of our is_digits function
- if (!isValid) { // If the entered string is not (!) valid, then do this:
- cout << "That is not a valid integer. Please try again." << endl << endl; // Tell them it's not valid and put two blank lines there
- }
- } while (!isValid); // While !isValid [in other words, while the entered string is not (denoted by exclamation point) valid], ask for a new string
- int iCurrInt, iSum = 0, iProduct = 1; // Create three new integer variables to store our desired output
- cout << "Will parse these integers: "; //Output that we will list the integers back
- for (int i = 0, l = sNums.length(); i < l; i++) { // Loop through the characters (numbers) in the string
- iCurrInt = sNums[i] - '0'; // Complicated to explain, but this will change the character into an integer we can use and store the new value
- cout << iCurrInt << " "; // Output the character and then a space
- iSum += iCurrInt; // Increment our iSum variable by the value of our current integer variable and then store it back into iSum
- iProduct *= iCurrInt; // Multiple our iProduct value by the value of our current integer variable and then store it back into iProduct
- }
- cout << endl; // Output an end-of-line character
- cout << "Sum of the given integers: " << iSum << endl; // Output text, then the sum, then an end-of-line character
- cout << "Product of given integers: " << iProduct << endl << endl; // Output text, then the product, then two end-of-line characters
- system("pause"); // Wait for the user to press a key before finishing the program and closing it
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement