问题是,当我第一次运行我的程序并输入5时,程序将返回星期五,然后按下y重新启动操作而不关闭控制台并输入9,程序将返回默认的错误消息,并将返回星期五,这在我的代码中是一个错误,我无法确定是什么导致了错误。“守则”:
#include <iostream>
#include <limits>
using namespace std;
enum Dayofweek {monday = 1 , tuesday = 2, wednesday = 3, thursday = 4, friday = 5, saturday = 6, sunday = 7};
string Day (Dayofweek);
int main()
{
int i;
char resTart;
Dayofweek d = monday;
do
{
cin.clear();
system ("cls");
cout << "Enter the day of a week:[1] [2] [3] [4] [5] [6] [7]: ";
while (!(cin >> i))
{
//system ("cls");
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
system ("cls");
cout << "Invalid Input detected, Only numbers are allowed. 1, 2, 3, 4 ,5 ,6 ,7. Try Again." << '\n';
cout << "Enter the day of a week: ";
}
cout << Day (Dayofweek (i)) << '\n';
do
{
cin.clear();
cout << "Do you want to Continue [Y/n]" << '\n';
cin >> resTart;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
system ("cls");
}while (resTart != 'Y' && resTart != 'y' && resTart != 'N' && resTart != 'n' );
}while (resTart == 'Y' || resTart == 'y');
}
string Day (Dayofweek d)
{
switch (d)
{
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
case 7:
return "Sunday";
default:
cout << "Invalid Input detected, Only numbers are allowed in limit to 7 days of week, Try Again." << '\n';
}
}控制台中的OutPut :输入一周中的一天:12 4 6: 9检测到无效输入,只允许输入数字。1,2,3,4 ,5 ,6 ,7.重试。星期五你想继续Y/n吗

发布于 2020-05-06 17:31:17
Day函数应该返回一个string。但是,在开关语句的string情况下,您不会返回一个default,该语句调用未定义的行为(在您的示例中,函数返回“星期五”,但任何事情都可能发生)。
您需要返回一些内容才能使程序定义良好:
string Day (Dayofweek d)
{
switch (d)
{
case 1:
return "Monday";
// etc ...
case 7:
return "Sunday";
default:
cout << "Invalid Input detected, Only numbers are allowed in limit to 7 days of week, Try Again." << '\n';
return "not a day";
}
}我强烈建议打开编译器中的所有警告(例如,使用gcc和clang,您可以将-Wall作为编译标志传递)。编译器会让您知道您正在做的事情可能是错误的。
发布于 2020-05-06 19:05:59
当执行结束时返回一个空字符串,值为无效。
string Day (Dayofweek d)
{
string null;
switch (d)
{
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
case 7:
return "Sunday";
default:
cout << "Invalid Input detected, Only numbers are allowed. 1, 2, 3, 4 ,5 ,6 ,7. Try Again." << '\n';
return string (null);
}
}https://stackoverflow.com/questions/61641404
复制相似问题