【问题标题】:can you set a string to a macro你可以给宏设置一个字符串吗
【发布时间】:2020-09-22 09:18:21
【问题描述】:

我试图让用户输入一种颜色,输出​​将是所选颜色的句子 我正在使用设置为变量的 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 而不是 color , 谢谢你 任何帮助将不胜感激

【问题讨论】:

  • C 中的宏是编译时字符串替换,因此不会影响运行时。您应该创建一个表和一个代码来查找该表。
  • 如果用户输入garbleprintf("%s hello test ", colour1)将打印garble hello test。现在如果用户输入blue,为什么printf("%s hello test ", colour1) 打印的不是blue hello test

标签: c colors header macros ansi


【解决方案1】:

您似乎对宏的理解很混乱。宏替换由预处理器执行,这是实际编译之前的一步。因此,在程序编译并实际运行之前,永远不能对用户输入执行宏替换!

这是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;
}

【讨论】:

    【解决方案2】:

    当您存储用户在colour1 中输入的“蓝色”或“红色”字符串时,您的printf 会将其替换为“蓝色你好测试”。但是你想要的是“\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 else,但是将定义映射到输入的概念保持不变。

    【讨论】:

      猜你喜欢
      • 2019-12-05
      • 2010-10-07
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      相关资源
      最近更新 更多