很抱歉代码比可能长得多。下面是“阶乘计数”的示例代码,其中包含输入符号及其处理。我试图展示不同的可能性。我现在看到的唯一问题是,如果用户在没有输入任何符号的情况下按 Enter 键,则没有任何反应。这是我在这里的第一篇文章,所以对于任何可能的字体、格式和其他废话,我感到非常抱歉。MaxNum = 21 是根据经验为 unsigned long long int 返回类型定义的。
我检查过这样的输入案例:abcde 2. -7 22 21
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cstdlib>
unsigned long long int CalcFact( int p )
{ return p == 0 || p == 1 ? 1 : p*CalcFact(p-1); }
int main()
{
int MaxNum = 21, HowMany = 0, MaxAttempts = 5, Attempts = 0;
char AnyKey[] = "", *StrToOut = "The factorial of ", Num[3] = "";
bool IsOK = 0;
while( !IsOK && Attempts++ < MaxAttempts )
{
std::cout << "Please enter an integer > 0 and <= 21: ";
std::cin.width(sizeof(Num)/sizeof(char));
std::cin >> Num;
for( int Count = 0; Count < strlen(Num); Count++ )
IsOK = isdigit(Num[Count]) ? true : false;
if( IsOK )
{
if( !(atoi(Num) >= 0 && atoi(Num) <= MaxNum) )
IsOK = false;
else
{
for( int Count = 0; Count <= MaxNum; Count++ )
{
std::cout << StrToOut << Count << std::setfill('.')
<< std::setw( Count < 10 ? 30 : 29 )
<< CalcFact(Count) << std::endl;
}
}
}
if( !IsOK && Attempts > 0 )
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
if( !IsOK )
return -1;
else
std::cin >> AnyKey;
return 0;
}