c - 带有大小写开关和枚举的工作日

标签 c enums switch-statement case

我正在尝试在 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;

    }

如何正确地写这个?

最佳答案

带有 %s 说明符的

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

不幸的是,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,而必须使用循环。

关于c - 带有大小写开关和枚举的工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55310431/

相关文章:

c++ - 什么是 "Clean C",它与标准 C 有何不同?

c - Rust bindgen无法找到平台特定的库?

c - 在 gcc 中出现错误但仍然成功运行

python ctypes,试图找到库名称

c# - 将枚举设置为其默认值

java - 在 HQL 查询中使用枚举列表作为参数

C++ 模板和重载运算符

java - 实现一个通用的 switch case

ios - UISegmentedControl 与 UICollectionView 错误与 Switch 语句

c++ - 切换并将 char 值添加到数组