Initialize const char* by concatenating another char*

北战南征 提交于 2019-12-02 05:30:13

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!