[英]Removing strings from an array in c
我有一个程序可以在字符串上调用白色、黑色、蓝色、红色和黄色。 所以我的问题是我将如何检查输入的字符串,然后打印未调用的颜色。
前任。 如果。 在我的函数中为字符串输入了白色、黑色、蓝色、黄色,程序需要打印红色,这是一种可能性,例如无效输入,例如狗、白色、鲸鱼、蓝色、黑色、红色等等应该打印出黄色
const char *string[5];
string[0] = "White";
string[1] = "Black";
string[2] = "Blue";
string[3] = "Red";
string[4] = "Yellow";
gets(string);
printf(//);
您可以简化字符串的声明,它应该是const
因为我们不会修改它:
const char *strings[] = { "white", "black", "blue", "red", "yellow" };
然后我们可以使用整数的位来表示已输入strings
中的值:
unsigned int flags = 0; /* Zero has no bits set => nothing input so far. */
当我们得到一个输入时,我们会在strings
查找匹配项,并在flags
设置相应的位:
char input[1024];
if(fgets(input, sizeof input, stdin) != NULL)
{
const size_t len = strlen(input);
while(len > 0 && input[len - 1] == '\n')
input[--len] = '\0';
for(size_t i = 0; i < sizeof strings / sizeof *strings; ++i)
{
if(strcmp(strings[i], input) == 0)
flags |= 1 << i;
}
}
然后最后打印所有没有见过的strings
:
for(size_t i = 0; i < sizeof strings / sizeof *strings; ++i)
{
if((flags & (1 << i)) == 0)
printf("%s\n", strings[i]);
}
我希望你应该能够使用上面的部分来获得你想要的东西。
您可以使用枚举轻松做到这一点。
定义您要使用的颜色
typedef enum { WHITE = 0, BLACK, BLUE, RED, YELLOW } colors_t;
和一个数组来保存每个定义的颜色的字符串
const char * colors_str[] = {
[ WHITE ] = "White",
[ BLACK ] = "Black",
[ BLUE ] = "Blue",
[ RED ] = "Red",
[ YELLOW ] = "Yellow"
};
现在您可以将字符串与这样的颜色进行比较:
strcmp( string_input, colors_str[ i ] )
并使用计数器对我们作为输入给出的所有颜色数量求和,最后打印
printf( "%s", colors_str[ total - sum ] );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.