如何通过用户输入打印一周中的 7 天?

Arn*_*aba 5 c++ codeblocks

问题是当我第一次运行我的程序并输入 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';
    }
}
Run Code Online (Sandbox Code Playgroud)

OutPut in Console:输入星期几:1 [2] [3] [4] [5] [6] [7]:9 检测到无效输入,只允许数字。1、2、3、4、5、6、7。再试一次。星期五你想继续吗[是/否]

在此处输入图片说明

cig*_*ien 5

Day函数应该返回一个string. 但是,在 switch 语句stringdefault情况下,您不会返回 a ,这会调用未定义的行为(在您的情况下,函数返回“星期五”,但任何事情都可能发生)。

您需要返回一些东西才能使程序得到明确定义:

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

我强烈建议您打开编译器中的所有警告(例如,使用gcc, 和clang,您可以-Wall作为编译标志传递)。编译器会让你知道你正在做的事情可能是错误的。

  • 不用担心。请参阅有关打开警告的附加评论。 (2认同)
  • 好的,我一定会做到的) (2认同)