【问题标题】:C++ String Concatenation operator<<C++ 字符串连接运算符<<
【发布时间】:2014-02-27 00:03:31
【问题描述】:

我已经意识到我的错误了。我试图连接两个字符串。

我刚刚开始学习 C++。我有一个关于字符串连接的问题。 我使用时没有问题:

cout << "Your name is"<<name;

但是当我尝试使用字符串时:

string nametext;
nametext = "Your name is" << name;
cout << nametext;

我遇到了一个错误。如何连接两个字符串?

【问题讨论】:

  • name 还是std::string
  • &lt;&lt;cout 的“放入”运算符。它不适用于 std::string 或 C 样式字符串 (char *)。
  • 在未来,可以用 + 不能用 std::ostringstream 处理的东西来做这件事。

标签: c++ string string-concatenation


【解决方案1】:

首先不清楚类型名称有什么。如果它的类型为std::string,则不是

string nametext;
nametext = "Your name is" << name;

你应该写

std::string nametext = "Your name is " + name;

其中运算符 + 用于连接字符串。

如果name 是一个字符数组,那么您不能对两个字符数组使用运算符 +(字符串字面量也是一个字符数组),因为表达式中的字符数组被编译器隐式转换为指针。在这种情况下,你可以写

std::string nametext( "Your name is " );
nametext.append( name );

std::string nametext( "Your name is " );
nametext += name;

【讨论】:

    【解决方案2】:

    nametextstd::string,但它们不像输出流那样具有流插入运算符 (&lt;&lt;)。

    要连接字符串,您可以使用append 成员函数(或等效的+=,其工作方式完全相同)或+ operator,它通过连接前一个字符串创建一个新字符串两个。

    【讨论】:

      【解决方案3】:

      对于 C++ 中的字符串连接,您应该使用 + 运算符。

      nametext = "Your name is" + name;
      

      【讨论】:

      • 不起作用,我收到“二进制表达式的无效操作数('const char ' and 'const char *')”错误在于这一行:std::string helloWorld =“你好,”+“世界!”;我究竟做错了什么? “你好”和“世界!”是有效的字符串(我可以单独声明、分配和打印它们),但它引发了一些奇怪的错误 abour char ?
      • @GregoryFenn C++ 试图向后兼容 C,因此原始文字字符串 "string" 将是 const char* 而不是 C++ 字符串。在 c++ 中,您不能重载两边都采用原始类型的运算符,这意味着您必须将其中一个转换为字符串。这将起作用:std::string helloWorld = "Hello" + std::string(" World!");
      • 太棒了!这让它更清晰:) 我习惯了 C#,所以其中一些技术点对我来说似乎很奇怪,尝试向后兼容对我来说似乎很奇怪,但这只是我。
      • @GregoryFenn 是的,如果你事先不知道 C++ 中的原始文字字符串,它们会非常混乱
      【解决方案4】:

      您可以像这样使用流字符串组合字符串:

      #include <iostream>
      #include <sstream>
      using namespace std;
      int main()
      {
          string name = "Bill";
          stringstream ss;
          ss << "Your name is: " << name;
          string info = ss.str();
          cout << info << endl;
          return 0;
      }
      

      【讨论】:

        【解决方案5】:

        nametext = "Your name is" + name;

        我认为应该这样做

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-07
          • 2016-07-19
          • 2015-08-28
          • 2010-09-08
          • 1970-01-01
          • 2017-03-29
          • 2012-05-07
          • 2015-01-11
          相关资源
          最近更新 更多