我正在尝试编写一个程序,该程序输入一个数字和一个数字,并打印该数字包含在数字中的次数。我试图使该程序适用于不合适的用户输入数据,但是当用户输入字符串或单个字符而不是数字时,该变量将获得等于0的赋值。 这是程序的代码:
#include <iostream>
#include <limits>
using namespace std;
int SafelyInputInteger(long long lowerBound, long long upperBound) // A function which prevents errors caused by inappropriate data input FOR THE NUMBER
{
long long intNumber;
do {
cout<<"Input a number: "; cin>>intNumber;
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
continue;
}
} while((intNumber<lowerBound)||(intNumber>upperBound));
return intNumber;
}
int SafelyInputDigit() // A function which prevents errors caused by inappropriate data input FOR THE DIGIT
{
int intNumber;
do {
cout<<"Input a digit: "; cin>>intNumber;
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
continue;
}
} while((intNumber<0)||(intNumber>9));
return intNumber;
}
int howManyTimes(long long number, int digit) // A function that counts the times a given number contains a given digit
{
int counter=0;
while(number>0)
{
if(digit==number%10) {counter++;}
number/=10;
}
return counter;
}
int main()
{
const long long SMALLESTVALUE=-4294967296; // -4294967296=-2^32
const long long BIGGESTVALUE=4294967295; // 4294967295=2^32-1
long long inputNumber;//The number whose digits we will evaluate
int inputDigit;//The digit that we are going to search for in the number
inputNumber=SafelyInputInteger(SMALLESTVALUE,BIGGESTVALUE);
inputDigit=SafelyInputDigit();//Digits are numbers between 0 and 9
cout<<inputNumber<<" contains "<<inputDigit<<" "<<howManyTimes(inputNumber,inputDigit)<<" times.\n";
return 0;
}