错误C2664:'sprintf':无法将参数1从'std :: string'转换为'char*'

har*_*ari 1 visual-c++

下面是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();
}
}
Run Code Online (Sandbox Code Playgroud)

每当我运行这个获取错误.然后,我改变了char tempbuf[50];std::string str1;.
现在它显示:

Error C2664: 'sprintf' : cannot convert parameter 1 from 'std::string' to 'char *;
Run Code Online (Sandbox Code Playgroud)

amount变量包含float值.如何复制浮点值将其赋值给字符串变量?

Ale*_*lex 5

您正在将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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

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

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