【问题标题】:Combining two const char* together将两个 const char* 组合在一起
【发布时间】:2013-09-05 23:29:04
【问题描述】:

我尝试了很多方法来做到这一点,我得到了一个静态的 void,并且在我制作的控制台类上,Void 它自己工作正常:

Console::WriteLine(const char* msg)

另一方面,我得到了另一个 const char* non static void,它从中调用 Console::WriteLine void,我已经在 C# 上工作了大约一年,在 C# 上我可以轻松地做这样的事情:

string a = "Start ";
string b = a + "End";

当我在 C++ 上调用它时,它给了我一堆错误:

Player::Kill(const char* Message)
{
    Console::WriteLine("> " + Message + " <");
}

我也尝试过 strcat 的东西,但它告诉我使用 strcat_s 这并没有真正起作用,而且我尝试使用字符串而不是 const char*,并尝试使用 char*,但是所有他们中的一些对我正在尝试做的事情给出了错误。

【问题讨论】:

  • 使用std::string
  • @Rapptz 正如您在上面看到的,我已经尝试过 std 字符串库,但它给了我错误。
  • 它会给你什么错误?
  • @WARLOCK,你必须更具体。这是正确的做法。如果是WriteLine,则采用const char *。让它接受const std::string &amp;
  • 欢迎来到 Stack Overflow。为了获得最佳响应,除了显示您所做的研究并在可能的情况下提供sscce 之外,您还应该尝试发布您遇到的编译器错误的全文。请参阅how to ask questions 部分。

标签: c++ string char constants


【解决方案1】:

好吧,可以用 const char* 进行更改,即使是 const 我们也无法更改其值但可以更改其地址,请查看下面的类以供参考

    class String
{
private:
    const char* m_Name;
    int m_Size;
public:
    String() :m_Name(" "), m_Size(0) { m_Size = 0; }
    String(const char* name , int size) :m_Name(name),m_Size(size) {}
    String(const char* name) :m_Name(name) {}

    void Display()
    {
        LOG(m_Name);
    }
    int GetSize()
    {
        while (m_Name[m_Size] != '\0')
        {
            m_Size++;
        }
        return m_Size;
    }
    void Append(const char* nameToAppend)
    {
        //Create an empty char array pointer "*tempPtr" of size = existing const 
        //char name pointer "m_Name"  + const char pointer appending name 
        //"*nameExtention" 
        
        //this array can store both the names 
        int totalSize = 0;
        int nameToAppendSize = 0, existingNameSize = 0;
        while (nameToAppend[nameToAppendSize] != '\0')
        {nameToAppendSize++;}
        existingNameSize = this->GetSize();
        totalSize = nameToAppendSize + existingNameSize;
        char* tempPtr = new char[totalSize+1];

        //Add  existing const char name pointer "*m_Name"  +  const char pointer 
        //appending name "*nameExtention" to tempPtr,  using a loop 
        
        int currentSize = 0;
        for (int i = 0; i < existingNameSize; i++)
        {   
            tempPtr[currentSize] = m_Name[i];
            currentSize++;
        }
        for (int i = 0; i <= nameToAppendSize; i++)
        {
            if (i == nameToAppendSize)
            {
                tempPtr[currentSize] = '\0'; // this line tells compiler to stop 
                                             //  writting inside tempPtr 
            }
            else
            {
                tempPtr[currentSize] = nameToAppend[i];
                currentSize++;
            }
        }
        //--------------------------------
        //Now change the address of your const char* with tempPtr
        //This will change the contents of the const char* 
        //--------------------------------
        m_Name = (char*)tempPtr;
    }
};

        

【讨论】:

    【解决方案2】:
    #include <iostream>
    using namespace std;
    
    string string1 = "John";
    string string2 = "Smith";
    
    float string1Len = string1.length();
    float combinedLen = string1.length() + string2.length();
    char combine[string2.length() + string1.length()];
    
    for(int i = 0; i < string1Len; ++i){
        combine[i] = string1[i];
    }
    for(int i = string1Len; i < combinedLen; ++i){
        combine[i] = string2[i - string1Len];
    }
    
    const char * combined = combine;
    

    【讨论】:

      【解决方案3】:

      char * 是指针("&gt; "" &lt;" 也是如此),不能将指针相加。

      但是,您可以使用 + 运算符连接 C++ 字符串:

      Player::Kill(const std::string& Message)
      {
          Console::WriteLine(("> " + Message + " <").c_str());
      }
      

      【讨论】:

      • IntelliSense: no operator "+" 匹配这些操作数操作数类型是:const char [3] + const std::string
      【解决方案4】:

      “const”的意思是“不能改变(*1)”。因此,您不能简单地将一个 const char 字符串“添加”到另一个 (*2)。您可以做的是将它们复制到非常量字符缓冲区中。

      const char* a = ...;
      const char* b = ...;
      
      char buffer[256]; // <- danger, only storage for 256 characters.
      strncpy(buffer, a, sizeof(buffer));
      strncat(buffer, b, sizeof(buffer));
      
      // now buffer has the two strings joined together.
      

      您使用 std::string 的尝试因类似原因而失败。你说:

      std::string a = "Start";
      std::string b = a + " End";
      

      这转化为

      b = (std::string)a + (const char*)" End";
      

      除了创建一个额外的字符串之外应该没问题,你可能想要的是

      std::string a = "Start";
      a += " End";
      

      如果您在执行此操作时遇到编译错误,请发布它们(确保您 #include )。

      或者你可以这样做:

      std::string addTwoStrings(const std::string& a, const std::string& b)
      {
          return a + b; // works because they are both strings.
      }
      

      以下所有工作:(见现场演示http://ideone.com/Ytohgs

      #include <iostream>
      #include <string>
      
      std::string addTwoStrings(const std::string& a, const std::string& b)
      {
          return a + b; // works because they are both strings.
      }
      
      void foo(const char* a, const char* b)
      {
          std::string str = a;
          std::cout << "1st str = [" << str << "]" << std::endl;
          str += " ";
          std::cout << "2nd str = [" << str << "]" << std::endl;
          str += b;
          std::cout << "3rd str = [" << str << "]" << std::endl;
          str = addTwoStrings(a, " ");
          std::cout << "4th str = [" << str << "]" << std::endl;
          str = addTwoStrings(str, b);
          std::cout << "5th str = [" << str << "]" << std::endl;
      }
      
      int main()
      {
          foo("hello", "world");
      }
      

      *1 或者更准确地说,“不能原地改变”——你可以在表达式等中使用它,例如,例如,例如

      const size_t len = strlen("hello");
      size_t newLen = len + strlen("world");
      // but this would not be legal:
      len += 2; // error: len is const.
      

      2 "const char a + const char* b" 实际上是试图添加两个 pointers 而不是两个字符串,结果将是字符串 a 的地址加上字符串 b 的地址,其总和将是某个随机内存位置

      【讨论】:

      • const 表示您不能将结果保存在该变量 (const char) 或位置 (const char *) 中。他对 + 的问题是两个指针不能加在一起(const char *a, *b, *c; c = a + b; a 和 b 是指针,而 + 在指针之间无效,现在 c = a + 10; 工作得很好)。与 const 本身无关。无论如何,结果都会传递给函数。您的第二个示例也可以正常工作:a + " End" 在 a 是 std::string 时完全有效。 " End" 是一个 const char *,它被用作只读输入字符串!
      • 还根据您的 cmets 合并了对第二个字符串示例的更改。
      • @WARLOCK 为了正确起见,它实际上与“const”无关。只是你不能添加指针(当你写"&gt; " + Message时,左操作数"&gt; "被转换为const char*即指针)。但是运算符+overloaded,尤其是(string, string),但也适用于(string, const char*)(const char*, string) 的组合,所以string b = a + " End"; 实际上是works fine(即使aconst)。 (@kfsone downvote 不是来自我)编辑:哇 3 个新的 cmets!
      • 奇怪 - 它没有显示已编辑,但我可以发誓我得到了“const char*” a 和 b 并尝试从帖子中使用 strcat 等。也许我是从一个已被删除的答案中挑选出来的。
      • @kfsone 确实有可能,因为帖子(答案或问题,初始或编辑)可以在提交后 5 分钟内由其作者修改,而不会在修订历史中“留下痕迹”(这就是之后如何“快速”的 cmets 会出现“离题”^^)
      【解决方案5】:

      与其连接字符串并创建一个额外的临时对象,为什么不单独输出 3 个字符串呢?

      Player::Kill(const char* Message)
      {
        Console::Write("> ");
        Console::Write(Message);
        Console::WriteLine(" <");
      }
      

      【讨论】:

        【解决方案6】:

        既然你说是C++代码,就这样吧:

        void Player::Kill(std::string const& Message)
        {
            Console::WriteLine(("> " + Message + " <").c_str());
        }
        

        理想情况下,您的Console::WriteLine() 也被声明为采用std::string const&amp;,在这种情况下您不需要进行.c_str()-dance。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多