枚举和字符串 [英] Enum and strings
本文介绍了枚举和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int main()
{
enum a {cat, dog, elephant};
enum a b;
b=dog;
if (b==dog) printf("Y"); else printf("N");
return 0;
}
上面的程序可以工作。它显示 Y
。但是我看不到它非常有用,所以我想做一些类似的东西,但是使用字符串:
The program above works. It shows Y
. But I do not see it very useful, so I want to make something similar, but with strings:
int main()
{
enum a {cat, dog, elephant};
enum a b;
char s[100];
gets(s);
b=dog;
if (b==s) printf("Y"); else printf("N");
return 0;
}
即使 s ==dog
,它不工作。
推荐答案
尝试以下方法
#include <stdio.h>
#include <string.h>
int main(void)
{
enum Animal { cat, dog, elephant };
char * animal_name[] = { "cat", "dog", "elephant" };
enum Animal b;
size_t n;
char s[100];
fgets( s , sizeof( s ), stdin );
n = strlen( s );
if ( s[n - 1] == '\n' ) s[n - 1] = '\0';
b = dog;
if ( strcmp( animal_name[b], s ) == 0 ) printf( "Y\n" );
else printf( "N\n" );
return 0;
}
如果要输入 dog
然后输出是
Y
在比较字符串之前,您可以将输入的字符串转换为动物名称数组的字符串中使用的小写。
Also before comparing strings you could convert the entered string to the lower case that is used in strings of the array of animal names.
或者您可以使用C#而不是可以将枚举器转换为字符串的C。 :)
Or you could use C# instead of C where enumerators can be converted to strings. :)
这篇关于枚举和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文