Initialize const char* by concatenating another char*

后端 未结 1 702
北海茫月
北海茫月 2021-01-24 06:31

I want to refactor:

const char* arr = 
  \"The \"
  \"quick \"
  \"brown\";

into something like:

const char* quick = \"quick \"         


        
相关标签:
1条回答
  • 2021-01-24 07:05

    Compiling the comments in the form of an answer:

    1. Use a macro.

      #define QUICK "quick "
      
      char const* arr = "The " QUICK "brown";
      
    2. Use std:string.

      std::string quick = "quick ";
      std::string arr = std::string("The ") + quick + "brown";
      

    Working code:

    #include <iostream>
    #include <string>
    
    #define QUICK "quick "
    
    void test1()
    {
       char const* arr = "The " QUICK "brown";
       std::cout << arr << std::endl;
    }
    
    void test2()
    {
       std::string quick = "quick ";
       std::string arr = std::string("The ") + quick + "brown";
       std::cout << arr << std::endl;
    }
    
    int main()
    {
       test1();
       test2();
    }
    

    Output:

    The quick brown
    The quick brown
    
    0 讨论(0)
提交回复
热议问题