首页 文章

C用字符串连接const char *,只打印const char *

提问于
浏览
1

我想尝试一个常见问题*

这是我如何将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;

打印时的结果是:分数:

有谁知道为什么6不打印?

提前致谢 .

2 回答

  • 0

    正如docs for c_str所说,"The pointer returned may be invalidated by further calls to other member functions that modify the object."这包括析构函数 .

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

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

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

    在这里,你在一个继续存在的字符串上调用 c_str .

  • 6

    您已将此帖标记为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*
    

相关问题