微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

您可以将字符串设置为宏吗

如何解决您可以将字符串设置为宏吗

我试图让用户输入一种颜色,输出​​将是所选颜色中的句子 我正在使用ansi转义码设置为变量,并且我不确定如何处理最后一个

#define red "\033[1;31m"
#define green "\033[0;32m"
#define blue "\033[0;34m"
#define magenta "\033[0;35m"
#define yellow "\033[0;33m"
#define cyan "\033[0;36m"

  int main() 
  {
        char colour1[10];

        printf("enter a colour");
        scanf("%s",colour1);

        
        printf("%s this is test\n ",red);
        printf("%s another test \n",green);
        printf("%s hello test ",colour1);

        return 0;
}

所以说,如果用户要输入“ blue”,它将只输出单词blue而不是color, 谢谢 任何帮助都会被感谢

解决方法

您似乎对宏有困惑的理解。宏替换由预处理器执行,这是实际编译之前的一步。因此,永远不能对用户输入执行宏替换,而用户输入只有在程序被编译并实际运行后才会出现!

这里是this comment中建议的基于工作查找表的实现的示例。

#include<string.h>
#include<stdio.h>

typedef struct colortable_t
{
  char* name;
  char* code;
} colortable_t;

const colortable_t colortable[] = 
{
  { "red","\033[1;31m" },{ "green","\033[0;32m" },{ "blue","\033[0;34m" },{ "magenta","\033[0;35m" },{ "yellow","\033[0;33m" },{ "cyan","\033[0;36m" },};

const char *color_lookup(const char *str)
{
  for(int i = 0; i < sizeof(colortable) / sizeof(colortable_t); i++)
  {
    if(strcmp(colortable[i].name,str) == 0)
      return colortable[i].code;
  }
  return "";
}

int main() 
{
  char colour1[10];

  printf("enter a colour");
  scanf("%s",colour1);

  printf("%s this is test\n ",color_lookup("red"));
  printf("%s another test \n",color_lookup("green"));
  printf("%s hello test ",color_lookup(colour1));

  return 0;
}
,

在存储字符串时,在colour1中输入的用户是“ blue”或“ red”,您的printf会将其替换为“ blue hello test”。但是,您需要的是“ \ 033 [0; 34m hello test”。为此,您需要以某种方式将用户的输入映射到您的颜色定义。

这可能看起来像这样:

//mapping and setting colour
if( 0 == strcmp(colour1,"blue") ) {
   printf( %s,blue );
} else if ( 0 == strcmp(colour1,"red") ) {
   printf( %s,red);
} else if (...) {
  ...
}

//printing your text
printf( "hello test\n" );

C对于字符串不是很好,我想还有很多其他方法可以将用户的输入映射到颜色,但是这应该给您预期的结果。如其他人所述,实现查找表可能不如我在这里显示的那样具有if if,但是将您的定义映射到输入的概念保持不变。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。