【问题标题】:How to combine strings and ints to a single string (C++) [duplicate]如何将字符串和整数组合成一个字符串(C++)[重复]
【发布时间】:2012-11-28 02:57:59
【问题描述】:

可能重复:
C++ concatenate string and int

我正在尝试使用多个字符串和整数来创建单个字符串,但我收到消息:“错误 C2110:'+':无法添加两个指针”

这是我的代码:

transactions[0] = "New Account Made, Customer ID: " + ID + ", Customer Name : " + firstName + " " + secondName + endl + ", Account ID: " + setID + ", Account Name: " + setName;

(注意ID和setID是一个i​​nt)

【问题讨论】:

  • 尝试使用'\n' 而不是endl

标签: c++ string pointers int


【解决方案1】:

使用字符串流:

#include <sstream>

...
std::stringstream stm;
stm<<"New Account Made, Customer ID: "<<ID<<", Customer Name : "<<firstName<<" "<<secondName<<std::endl<<", Account ID: "<<setID<<", Account Name: "<<setName;

然后您可以使用 stm.str() 访问生成的字符串。

【讨论】:

    【解决方案2】:

    您应该使用字符串流:将字符串写入其中;然后写int。最后通过流的str()方法收获结果:

    stringstream ss;
    string hello("hello");
    int world = 1234;
    ss << hello << world << endl;
    string res = ss.str();
    cout << res << endl;
    

    这是link to a demo on ideone

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-13
      • 2016-07-28
      • 1970-01-01
      • 2017-11-14
      • 2019-03-22
      • 2013-12-25
      • 1970-01-01
      • 2011-08-01
      相关资源
      最近更新 更多