【发布时间】:2018-05-11 20:57:35
【问题描述】:
我正在尝试编写一个程序,该程序根据拨打电话的时间、星期几和通话时长来计算通话费用。它必须是所有按值调用的函数并输出重复程序的选项。
我的问题是,当我输入一个无效的时间输入(例如 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;
}
【问题讨论】:
-
您没有检查
validateUserInputTime返回的内容。你需要像if (result == false) { ... }这样的代码,其中大括号中的代码与validateUserInputCallLength之后的代码相似 -
如果没有minimal reproducible example,您的问题就离题了。
-
我只发表评论是因为我花了一点时间才意识到“科林”是什么。 ':' 拼写为冒号。
-
我一定是不小心删除了if语句,我刚刚编辑了它,我应该如何更正我的问题以成为主题,我很抱歉我会将它修复为冒号。
-
我建议您改为从用户那里读取该行,然后分析该行。例如使用 std::getline,然后解析字符串。这样您就可以更好地控制用户输入的内容。
标签: c++ call-by-value