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

时间:2011-12-27 10:14:54

标签: 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();
}
}

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

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

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

4 个答案:

答案 0 :(得分: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;
}

编辑:

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

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

答案 1 :(得分:2)

使用std::stringstream(您需要包含<sstream>):

float amount = 3.14159;
std::stringstream ss;

ss << amount;

std::string tempbuf = ss.str();

答案 2 :(得分:2)

sprintf需要char *但不是std :: string

int sprintf ( char * str, const char * format, ... );

你可以使用ostringstream代替

ostringstream oss1;
oss1 << (analysis->peak + j)->amount;
oss1.str();

答案 3 :(得分:1)

你不应该使用sprintf作为stl字符串,而是使用ostringstream:

#include <sstream>
#include <string>
#include <iostream>
using namespace std;

/// ...

ostringstream strstr;
strstr << (analysis->peak + j)->amount;
str += str.str()