visual-c++ - 错误 C2664 : 'sprintf' : cannot convert

下面是VC++中的插入函数。 当我将 char 更改为字符串数据类型以读取以下代码中的 amount 变量的值时,出现此错误。

static void Insert(t_analysis* analysis)    
{    
 _bstr_t strunitId;    
 _bstr_t strGdt=time(0);    
_bstr_t strvalue;   
    std::string str;
std::string commandStr = "insert into table1(unitid,g_time_dte_1,h_1,n_1,ch_1,co_1,im_1,ve_1,er_1) Values(123,'" + strGdt +"',";
    char tempBuf[50];
for (int j = 0; j < analysis->ubPeaksIntTab;j++ )
{   
    sprintf(tempBuf, "%d", (analysis->peak + j)->amount);//here it takes the adrress of amount but not the value of amount variable.
    str += commandStr + tempBuf;
    if(j!=analysis->ubPeaksIntTab-1)
       commandStr += ",";
}

commandStr += ")";
_ConnectionPtr pConn = NULL;

try
{       
    HRESULT hr = S_OK;
    CoInitialize(NULL);
    hr = pConn.CreateInstance((__uuidof(Connection)));
    _bstr_t strCon("Provider=SQLOLEDB;Dataq Source=MYPC\\SQLEXPRESS;Initial Catalog=keerth;User ID=sa;Password=password;Connect Timeout=30;");

    if(FAILED(hr))
    {
        printf("Error instantiating Connection object\n");

    }

    hr = pConn->Open(strCon,"sa","password",0);

    if(FAILED(hr))
    {
        printf("Error Opening Database object using ADO _ConnectionPtr \n");

    }

    //Execute the insert statement
    pConn->Execute(commandStr.c_str(), NULL,adExecuteNoRecords);
    pConn->Close();
}
catch(_com_error &ce)
{
    printf("Error:%s\n",ce.ErrorMessage());
    pConn->Close();
}
}

每当我运行这个得到错误。然后我将 char tempbuf[50]; 更改为 std::string str1;
现在显示:

Error C2664: 'sprintf' : cannot convert parameter 1 from 'std::string' to 'char *;

金额变量包含浮点值。 如何复制浮点值并将其分配给字符串变量?

最佳答案

您正在将 C++ 与 C 标准库函数混合使用。

您应该使用 C++ 原语。参见 StringStreams

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

int main () {
  std::stringstream ss;
  ss << "hello world";
  ss << 45;
  ss << std::endl;
  std::string foo = ss.str();
  std::cout << foo;
  return 0;
}

编辑:

如果你想在 C 中实现相同的逻辑:std::string 类型不是 C 类型,C 的标准字符串类型是 char *const char * 用于不可变字符串。

您要查看的函数是:strncat(连接字符串)和更安全的snprintf

关于visual-c++ - 错误 C2664 : 'sprintf' : cannot convert parameter 1 from 'std::string' to 'char *' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8643479/

相关文章:

sql - 如何从 SQL Server 获取数据库列表?

c# - 如何判断对象初始化程序何时完成

erlang - 在没有列表到字符串翻译的情况下格式化 Erlang 术语

ruby-on-rails - Errno::ETIMEDOUT:连接超时 - connect(2)

php - php preg匹配中的 "*"和 "?"有什么区别?

logging - 如何在 Glassfish 中设置日志记录级别?

jquery - 如何使用 jQuery 取消按钮的提交

bash - 在 bash 中,如何在键入命令行时扩展 !$?

objective-c - Xcode - 将 CGRect 转换为 ID?

visual-c++ - 为什么没有定义 PCTSTR 但定义了 LPCTSTR?