c - 从 sqlite 中检索字符串形式的数字并转换为 int

标签 c sqlite

我正在使用 sqlite3 来存储应用程序的数据。代码的近似如下:

static int callback(void *data, int argc, char **argv, char **azColName){

    char temp[50];
    int temp_int;

    strcpy(temp, argv[1]); //this works, strcpying from a string to a string 
    temp_int = argv[2]; // this yields an unexpected number

}

    rc = sqlite3_exec(db, sqlRetreive, callback, (void*)data, &zErrMsg);

我相信这是预期的,因为对 sqlite 的调用将所有内容作为字符串拉动(我相信)。我尝试使用 (int) 对其进行强制转换,如 temp_int = (int) argv[2]; 中所示但这会产生一个略有不同的意外数字。

是否有办法将特定列提取为整数?或者一种方法来转换它以接收我们最初存储的 int?c

最佳答案

即使进行重铸,也不能直接将字符串指定为整数。使用 <stdlib.h> 代替库函数“strtol()

#include <stdlib.h>

long temp_int;
char *ptr;     // temporary pointer

temp_int = strtol(argv[2], &ptr, 10);   // the '10' here means base-10

if (ptr == argv[2])  // no valid numeric was found to convert
{ 
    // failure occurred, string was not a base 10 numeric
    // so, handle appropriately
}

// otherwise, your temp_int now has the converted value

检查 strtol() 的文档。 http://www.cplusplus.com/reference/cstdlib/strtol/

应始终使用 strtol() 而不是 atoi()。如果 &ptr 移至转换字符串的末尾,strtol() 将显示成功。 atoi() 不提供任何错误检查的可能性,并表明程序员缺乏经验。

关于c - 从 sqlite 中检索字符串形式的数字并转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46395883/

相关文章:

ruby-on-rails - 在更改我的开发数据库之前我应该​​知道什么?

c++ - 如何将 sqlite3 + 扩展函数静态链接到 C/C++ 应用程序中?

用于存储sqlite db的C代码不将数据存储在物理内存中

c - C中的字符串分隔和格式化

c - 我的 MPI 雅可比迭代程序给出了错误的结果

c - Mac OS Maverick for C 的基本 Cmake 和 make

c# - 在 Xamarin Android 中存储 SQLite 数据库的路径

iphone - 在 iOS 应用程序中使用 .mdb 文件而不是 SQLite?

c - 指向结构体指针的指针

c - 对这一灾难性声明的解释正确吗?