【问题标题】:cast from 'char*' to 'int' loses precision从 \'char*\' 转换为 \'int\' 失去精度
【发布时间】:2022-12-31 19:05:20
【问题描述】:

在 64 位机器中将 char* 转换为 am 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' 会丢失精度)

【问题讨论】:

  • 您首先要通过将 char * 转换为 int 来实现什么目的?
  • 你有没有想过为什么你需要这么多变量? query = stmt.str(); q = query.c_str(); mysql_query(conn, q); 可以替换为 mysql_query(conn, stmt.str().c_str()); 并且两个变量和两行代码已被删除。调用函数时不必使用变量,可以使用表达也。
  • row 的类型是什么? (我没有看到它的声明。)

标签: c++


【解决方案1】:

int 更改为 std::intptr_t,包括数组声明。为此你需要#include &lt;cstdint&gt;

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

【讨论】:

  • 我不认为从 char* 转换为 int(或 intptr_t)是 OP 真正想要的。
【解决方案2】:

标准库有两个固定宽度的typedefs,能够保存指向void的指针,它们在&lt;cstdint&gt;中定义:

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 

【讨论】:

    【解决方案3】:

    您需要 long long,而不是 long 来执行转换。但我怀疑这根本无法解决您的问题。

    【讨论】:

    • long long 解决了转换问题,但它给了我一个错误,未定义引用代码使用的所有 mysql 函数
    • 反对票是不受欢迎的。我确实回答了这个问题并发出了警告。
    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 2010-12-11
    • 1970-01-01
    • 2015-12-07
    • 2021-11-09
    • 2015-03-17
    • 1970-01-01
    相关资源
    最近更新 更多