【问题标题】:Trouble using a string with the sprintf() function在 sprintf() 函数中使用字符串时遇到问题
【发布时间】:2015-01-27 12:17:25
【问题描述】:

我希望这将是一个非常基本的问题,这可能是由于我对很多 C++ Win32 API 实用程序缺乏了解。

无论如何,我在使用 sprintf() 函数时遇到了一些问题。我用这样的字符串没有问题:

//memory is a void pointer that maps a file to shared memory
sprintf((char *)memory, "Shared memory message"); //Write to shared memory

但是当我尝试使用 string 变量时它不起作用....

sprintf((char *)memory, str_var); //Write to shared memory

我收到一条错误消息:no suitable conversion function from "std::string" to "const char *" exists。我什至无法通过类型转换来解决这个问题,就像我对 memory 所做的那样。

这似乎很不一致。我做错了什么,我该如何给它一个它会接受的值?

【问题讨论】:

标签: c++ string shared-memory


【解决方案1】:

如果你需要sprintf,你需要传递一个const char*

例如

sprintf((char *)memory, str_var.c_str()); 

【讨论】:

    猜你喜欢
    • 2014-01-08
    • 2014-12-05
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多