Search code examples
ccolorsheadermacrosansi-c

can you set a string to a macro


I am trying to get a user to enter a colour and the output will be the sentence in the chosen colour I am using ansi escape codes set as variable, and im not sure on how to work the last one

#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;
}

so say if the user was to enter "blue" it would just output the word blue and not the colour , thank you any help would be mutely appreciated


Solution

  • Your seem to have a confused understanding of macros. Macro substitution is performed by the pre-processor and this is one-step before the actual compilation. Hence macro substitution can never be performed on user input which does not come in until the program is compiled and actually run!

    Here is an example of a working lookup-table based implementation suggested in 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;
    }