我正在尝试编写一个程序,该程序根据拨打电话的时间、星期几和通话时间来计算通话费用。它必须是所有按值调用的函数并输出重复程序的选项。
我的问题是,当我输入一个无效的时间输入(例如 a:37)时,它会输出无效输入,但会继续输入当天的输入,而不是返回到时间输入。我是一名新程序员,并且已经尝试了我能想到的一切来修复它,但它要么陷入整个程序退出的无限循环中。
提前感谢您的帮助!
#include <iostream>
using namespace std;
bool validateUserInputTime(int,char,int);
bool validateUserInputDay(string);
bool validateUserInputCallLength(int);
double calculateTotalCost(int,int,string,int);
string days[]={"Mo" , "Tu" , "We" , "Th" , "Fr" , "Sa" , "Su"};
float cost,fcost;
int main()
{
int hour;
int min;
int time;
char colon;
char answer = 'y';
string day;
string s;
bool result;
while(answer =='y')
{
cout<<"Enter the time the call starts in 24-hour rotation: "<<endl;
cin>>hour>>colon>>min;
result=validateUserInputTime(hour,colon,min);
if(cin.fail())
{
cout << "Invalid time input."<<endl;
cout<<"Please try again."<<endl<<endl<<endl;
cin.clear();
}
day=validateUserInputDay(s);
if(cin.good())
{
cout<<"Enter the first two letters of the day of the week:";
cin>>day;
}
cout<<"Enter the length of the call in minutes:"<<endl;
cin>>time;
result=validateUserInputCallLength(time);
if(result==0)
{
cout<<"Invalid minute Input."<<endl;
cout<<"Please try again."<<endl<<endl<<endl;
continue;
}
fcost= calculateTotalCost(hour,min,day,time);
cout<<"Cost of the call: $" << fcost<<endl;
cout<<"Do you want to repeat the program?";
cin>>answer;
}
return 0;
}
bool validateUserInputTime(int hour1,char ch,int min1)
{
if (cin.fail())
{
cout << "Invalid time input."<<endl;
cout<<"Please try again."<<endl<<endl<<endl;
cin.clear();
}
if(hour1 < 0)
{
return false;
}
if(min1 < 0)
{
return false;
}
if(ch!=':')
{
return false;
}
else
return true;
}
bool validateUserInputDay(string s)
{
int next=0;
for(int i = 0; i < 7; i++)
{
if(days[i] == s){
next=1;
}
if(cin.fail())
{
cout<<"Invalid day inpuT."<<endl;
cin.clear();
}
}
if(next==1)
{
return true;
}
else
{
return false;
}
}
bool validateUserInputCallLength(int time2)
{
if(time2<0)
{
return false;
}
else
{
return true;
}
}
double calculateTotalCost(int hour3,int min3,string d,int time3)
{
if((d=="Sa")||(d=="Su"))
{
cost=0.15*time3;
}
else
{
if((hour3>=8)&&(min3<18))
{
cost=0.40*time3;
}
else
cost=0.25*time3;
}
return cost;
}