Reputation: 1481
Below is the insert function in VC++. I am getting this error when I change the char to string data type to read the value of amount variable in the below code.
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();
}
}
Whenever I run this getting the Error. Then I changed the char tempbuf[50];
to std::string str1;
.
Now it is showing:
Error C2664: 'sprintf' : cannot convert parameter 1 from 'std::string' to 'char *;
The amount variable contains the float value. How can I copy the float value assign it to string variable?
Upvotes: 2
Views: 4296
Reputation: 25641
You are mixing C++ with C standard library functions.
You should use the C++ primitives. See 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;
}
EDIT:
If you want the same logic in C: The type std::string is not a C type, the standard string type of C is char *
and const char *
for immutable strings.
The functions that you want to look at are then: strncat
(concatenate strings) and the safer snprintf
.
Upvotes: 5
Reputation: 19043
sprintf needed char* but not std::string
int sprintf ( char * str, const char * format, ... );
you can use ostringstream instead
ostringstream oss1;
oss1 << (analysis->peak + j)->amount;
oss1.str();
Upvotes: 2
Reputation: 49986
you should not use sprintf for stl string, use ostringstream instead:
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
/// ...
ostringstream strstr;
strstr << (analysis->peak + j)->amount;
str += str.str()
Upvotes: 1
Reputation: 55395
Use std::stringstream
(you'll need to include <sstream>
):
float amount = 3.14159;
std::stringstream ss;
ss << amount;
std::string tempbuf = ss.str();
Upvotes: 2