c++ - 转换 int 并将其与 char* 连接

标签 c++ g++

我想将 int 转换为 charchar* 然后将它与 char* 连接起来>/p>

for (int i = 1; i < mymap.size(); i++)
{
    char * s = "Scene";
    cout << mymap[s+i];
}

我试过这种方式

string s = "Scene";
string x = to_string(i);
s = s + x;
char* si = s.c_str();

但是我得到一个错误。

但这行得通:

const char* si = s.c_str();

但后来我尝试将它与 mymap 一起使用:

cout << mymap[si];

我收到一条错误消息说我必须使用 char* 而不是 const char*

最佳答案

可能有点过分,但你可以试试 stringstream:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main(int argc, char * argv[]) {
 char * a = "hello";
 int b = 11;

 stringstream sstm;

 sstm << a << b;

 string ans = sstm.str();
 char * ans2 = (char *) ans.c_str();

 cout << ans2 << endl;   //"hello11"

 return 0;

}

关于c++ - 转换 int 并将其与 char* 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17150182/

相关文章:

C++ 将方法指针作为模板参数传递

c++ - 在 C++ 中捕获 SIGSEGV 的成本

c++ - 带有此指针的 Memset POD 结构

c++ - friend 和成员二元运算符的消歧

c++ - std 容器在多线程环境中是否总是抛出异常?

C++:复杂类上的 2 个模板与 1 个模板特化

c++ - SFINAE + decltype 的 g++ 4.7 错误?

c++ - 结合FORTRAN和C++,链接错误

c++ - 继承带有默认参数的构造函数: Which compiler is correct?

templates - "expected initializer before ` < ' token"在全局命名空间中具有内联模板函数