#include <iostream>
int main() {
int fact = 1;
int num;
do {
std::cout << "Please enter number from 1 to 10: " << std::endl;
std::cin >> num;
} while (num < 1 || num > 10);
for (int i = 1; i <= num; ++i) {
fact *= i;
}
std::cout << "the factor is: " << fact << std::endl;
return 0;
}
It fails when enter a char or string value. It would be interesting fix it.
#include <iostream>
#include <string>
#include <stdlib.h>
usingnamespace std;
bool IsValidInput(const string& input, int& num);
int main(void)
{
string buffer;
int fact = 1;
int num = 0;
cout << "Enter a number between 1 and 10 (-1 to quit): ";
cin >> buffer;
while (buffer != "-1")
{
if (IsValidInput(buffer, num))
{
for (int i = 1; i <= num; ++i)
fact *= i;
cout << "The factor is: " << fact << endl;
}
else
{
cout << "Invalid input - number must be between 1 and 10\n ";
}
cout << "Enter a number between 1 and 10 (-1 to quit) (-1 to quit): ";
cin >> buffer;
}
system("pause");
}
// input must be an int and must be >= 1 && <= 10
// if input is correct input be will converted to an int and will be stored in num,
// otherwise num is unchanged
// returns true if input is correct otherwise false
bool IsValidInput(const string& input, int& num)
{
if (input.size() > 2)
returnfalse;
for (int i = 0; i < input.size(); i++)
if (!(input[i] > '0' && input[i] <= '9'))
returnfalse;
int tmp = atoi(input.c_str());
if ( tmp > 1 && tmp <= 10)
{
num = tmp;
returntrue;
}
returnfalse;
}