gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:40:53 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com