使用案例切换和枚举的周日

问题描述 投票:0回答:1

我正在尝试使用案例切换和C语言中的枚举创建一个程序。我想插入在我的枚举日中预设的工作日。该程序运行正常,但进入工作日时收到错误。代码如下所示:

#include <stdio.h>

int main(){

    enum days{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
    enum days weekDay;
    int i = 0;

    printf("Insert a week day: ");
    scanf("%s", weekDay);

    switch(weekDay){

    case Sunday:
        i=i+1;
        printf("Number of the day: %i", i);
        break;

    case Monday:
        i=i+2;
        printf("Number of the day: %i", i);
        break;

    (...)

    case Saturday:
        i=i+7;
        printf("Number of the day: %i", i);
        break;

    default:
        printf("Error. Please insert a valid week day.");
        break;

    }

我怎么能正确写出来?

c enums switch-statement case
1个回答
1
投票

scanf%s说明符扫描字符串,而不是enums。确保您了解您正在使用的所有数据类型!

不幸的是,C并不真正关心你为enum成员分配的实际名称:它们仅供你自己作为程序员使用,并且不能被程序本身访问。尝试这样的事情。

const char* names[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", NULL}; // The name of each day, in order

char buffer[16]; // A place to put the input
scanf("%15s", buffer); // Now `buffer` contains the string the user typed, to a maximum of 15 characters, stopping at the first whitespace

for(int i=0; names[i] != NULL; i++){ // Run through the names
    if(strcmp(buffer, names[i]) == 0){ // Are these two strings the same?
        printf("Day number %d \n", i+1); // Add one because you want to start with one, not zero
        return;
    }
}

printf("Sorry, that's not a valid day"); // We'll only get here if we didn't `return` earlier

我已将工作日名称存储为字符串,程序可以访问该字符串。但比较字符串需要strcmp函数而不是简单的==,所以我不能再使用switch-case,而是必须使用循环代替。

© www.soinside.com 2019 - 2024. All rights reserved.