从"char*"转换为"int"会失去精度



我在64位机器中将char*转换为int时遇到问题。我知道问题是64位的sizeof(char*)是8,sizeof(int)是4。下面是代码:

void books::update()
{
int b_id[100],qty[100],i=0,max;
stmt.str("");
stmt<<" Select book_id,qty from purchase where recieves ='T' and inv IS NULL;";
query=stmt.str();
q =query.c_str();
mysql_query(conn,q);
res_set=mysql_store_result(conn);
stmt.str("");
stmt<<" Update purchases set inv=1 where recieves ='T' and inv is NULL";
query=stmt.str();
q=query.c_str();
mysql_query(conn,q);
while((row=mysql_fetch_row(res_set))!=NULL)
{
b_id[i]=(int)row[0];
qty[i]= (int)row[1];
i++;
}
max=i;
for(i =0;i<max;i++)
{
stmt.str("");
stmt<<" update books set qty ="<< qty[i]<<"where id = "<<b_id[i]<<";";
query= stmt.str();
q= query.c_str();
mysql_query(conn,q);

}
cout<<" The order recieved has been updated .";

}

错误在这两行:

b_id[i]=(int)row[0];
qty[i]= (int)row[1];

我试图使用(long)而不是(int),期望它将我的int从4字节转换为8字节,我仍然得到相同的错误(从'char*'转换为'int'失去精度)

标准库有两个固定宽度的typedefs,可以保存指向void的指针,它们在<cstdint>中定义:

std::intptr_t   // signed
std::uintptr_t  // unsigned

但是,不能通过强制转换将C字符串转换为整数。必须以某种方式解释C字符串。例子:

#include <sstream>
// ...
// put the two C strings in an istringstream:
std::istringstream is(std::string(row[0]) + ' ' + std::string(row[1]));
// and extract the values
if(is >> b_id[i] >> qty[i]) {
// success
}

其他选项是使用std::stoistd::strtol。例子:

b_id[i] = std::stoi(row[0]); // may throw std::invalid_argument ...
qty[i] = std::stoi(row[1]);  // ... or std::out_of_range 

int更改为std::intptr_t,包括数组声明。你需要#include <cstdint>

c++中关于整数类型的更多信息:https://en.cppreference.com/w/cpp/types/integer

最新更新