我正在使用 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/