【问题标题】:C++ Concatenating const char * with string, only const char * printsC++ 将 const char * 与字符串连接,仅打印 const char *
【发布时间】:2016-02-08 17:11:46
【问题描述】:

我正在尝试计算一个 const char *

这就是我将 int 转换为字符串并将其与 const char* 连接起来的方法

char tempTextResult[100];
const char * tempScore = std::to_string(6).c_str();
const char * tempText = "Score: ";
strcpy(tempTextResult, tempText);
strcat(tempTextResult, tempScore);
std::cout << tempTextResult;

打印时的结果是:Score:

有人知道为什么 6 不打印吗?

提前致谢。

【问题讨论】:

  • 有什么理由不写std::string textResult = std::string("Score: ") + std::to_string(6); std::cout &lt;&lt; textResult &lt;&lt; std::endl
  • @SimonKraemer 好吧,这与打印值无关。我需要它来渲染我使用 SDL 制作的游戏中的文本。

标签: c++ string char


【解决方案1】:

正如docs for c_str 所说,“返回的指针可能会因进一步调用修改对象的其他成员函数而失效。”这包括析构函数。

const char * tempScore = std::to_string(6).c_str();

这使得tempScore 指向一个不再存在的临时字符串。你应该这样做:

std::string tempScore = std::to_string(6);
...
strcat(tempTextResult, tempScore.c_str());

在这里,您正在对继续存在的字符串调用 c_str

【讨论】:

  • 当然,在std::string 中积累全部内容会更好。
  • @SebastianRedl 好吧,这有点不可能,因为 SDL_ttf 需要一个 const char * 作为文本来呈现......
  • @OpenGLManiac 你刚刚设法使用了strcat,它还想要一个const char* 我认为你可以处理SDL_ttf
【解决方案2】:

您已将此帖子标记为 C++。

一种可能的 C++ 方法:(未编译,未测试)

std::string result;  // empty string
{
   std::stringstream ss;
   ss << "Score: "  // tempText literal
      << 6;         // tempScore literal
   // at this point, the values placed into tempTextResult 
   //    are contained in ss
   result = ss.str();    // because ss goes out of scope
}
// ss contents are gone

// ...   many more lines of code

// ... now let us use that const char* captured via ss
std::cout << result.c_str() << std::endl;
//                  ^^^^^^^ - returns const char*

【讨论】:

  • 嗯,我需要它是一个 const char *,这看起来像一个字符串(我不知道 stringstream 是什么所以我不确定)
  • @OpenGLManiac 好的......我已经附加了 c_str() 以便 ss 的结果是 const char*。
  • 添加提醒,ss 的有限范围(通过大括号)要求我创建 ss 内容并将其捕获到结果字符串中.. 以供以后使用。
  • @OpenGLManiac -- std::stringstream 可以被认为是基于 ram 的流......使用更简单,工作方式非常类似于 fstream(但没有打开和关闭),并且 ram 比(大多数) 替代品。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
相关资源
最近更新 更多