【问题标题】:Week days with case switch and enum带有 case switch 和 enum 的工作日
【发布时间】:2019-03-23 03:46:24
【问题描述】:

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

    }

我怎样才能正确地写这个?

【问题讨论】:

  • 我运行程序正常吗?这段代码编译成功没有警告吗?
  • scanf("%s", weekDay); 会产生警告,您需要先阅读这些警告。格式说明符%s 需要char* 类型的参数,但weekdayenum 类型。
  • 您使用的 scanf 不正确,很抱歉我没有时间给出完整的答案,这里有一些快速的 cmets。 1. 你还不了解 C 中的数据类型。 2. 你还不了解 scanf。 3. 您可能还需要了解指针。如果我是你,在你对 1、2 和 3 有更多了解之前,我会避免使用 scanf。

标签: c enums switch-statement case


【解决方案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,而必须使用循环。

【讨论】:

  • 嗯...其实我开始学编程了,为此我选择了C语言。而且我从未见过这个'strcmp'函数。我需要阅读一些关于此的文档。不过谢谢,顺便说一句。
  • @EbertRodrigues 没问题!与大多数高级语言相比,C 中的字符串有点令人困惑,因此我建议您首先坚持使用数字,直到您掌握了基本结构。你可能还会发现 Python 之类的东西更容易上手:Python 经常牵着你的手,而 C 真的会让你毫无预警地陷入困境。
猜你喜欢
  • 2011-02-06
  • 2021-08-22
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多