C++,程序输出无效输入,但继续通过循环

C++, program outputs invalid input but continues through loop

本文关键字:继续 循环 输入 程序 输出 无效 C++      更新时间:2023-10-16

我正在尝试编写一个程序,该程序根据拨打电话的时间,星期几和通话时长来计算通话费用。它必须是所有按值调用的函数,并输出一个选项来重复程序。

我的问题是当我输入无效的时间输入(例如 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;
}

尝试使用循环。循环将停止程序的进行,直到结果值为 true。

result = false;
while (!result)
{
cout<<"Enter the time the call starts in 24-hour rotation: "<<endl;
cin>>hour>>colin>>min;
result=validateUserInputTime(hour,colin,min);
}

您还忘了在 validateUserInputTime 上放置一个错误的返回语句。输入非数字字符也可能使程序崩溃,cin.ignore 碰巧修复了它。

if (cin.fail())
{
cout << "Invalid time input."<<endl;
cout<<"Please try again."<<endl<<endl<<endl;
cin.clear();
cin.ignore();
return false;
}

如果您想解析用户输入的内容,请执行类似操作

std::string time;
std::getline(std::cin, time);

现在检查是否有":"auto pos = time.find(':'); if (pos != -1) {}然后取出小时部分time.substr(0,pos)然后分钟部分time.substr(pos+1)然后检查它们是否有效 小时和分钟,例如stoi().

此外,最好do {} while ()而不是while (answer == 'y') {...}