Advertisement
Guest User

colorize.cpp

a guest
Nov 30th, 2015
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. /*
  2.  * colorize.cpp
  3.  *
  4.  * Auth: Sun Dro
  5.  * Desc: Find string in array and change color if found.
  6.  */
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <stdarg.h>
  12.  
  13. #include <vector>
  14. #include <string>
  15.  
  16. #define MAXMSG 512
  17.  
  18. #define COLOR_GREEN    "\x1B[32m"
  19. #define COLOR_RESET    "\033[0m"
  20.  
  21. typedef std::vector<std::string> MyArray;
  22.  
  23. char* change_color(char* str, ...)
  24. {
  25.     static char output[MAXMSG];
  26.     char string[MAXMSG];
  27.  
  28.     va_list args;
  29.     va_start(args, str);
  30.     vsprintf(string, str, args);
  31.     va_end(args);
  32.  
  33.     sprintf(output, "%s%s%s", COLOR_GREEN, string, COLOR_RESET);
  34.  
  35.     return output;
  36. }
  37.  
  38. void search_in_array(MyArray& pArray, const char *key)
  39. {
  40.     int i, n = pArray.size();
  41.     bool bFound = false;
  42.  
  43.     for (i = 0; i < n; i++)
  44.     {
  45.         if (strstr(pArray[i].c_str(), key) != NULL)
  46.         {
  47.             printf("String found: %s\n", pArray[i].c_str());
  48.             char *colored = change_color("%s", pArray[i].c_str());
  49.             printf("Changed color: %s\n", colored);
  50.             bFound = true;
  51.         }
  52.     }
  53.  
  54.     if (!bFound) printf("Can not find string with given key: %s\n", key);
  55. }
  56.  
  57. int main(int argc, char *argv[])
  58. {
  59.     MyArray sArray;
  60.     sArray.clear();
  61.  
  62.     if (argc < 2)
  63.     {
  64.         printf("Usage: %s [name]\n", argv[0]);
  65.         printf("Example: %s lectus\n", argv[0]);
  66.         exit(EXIT_FAILURE);
  67.     }
  68.  
  69.     sArray.push_back("lorem ipsum dolor sit amet");
  70.     sArray.push_back("consectetur adipiscing elit");
  71.     sArray.push_back("donec a diam lectus");
  72.     sArray.push_back("sed sit amet ipsum mauris");
  73.  
  74.     search_in_array(sArray, argv[1]);
  75.  
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement