2012-03-21 31 views
1

我试图从数据库结果这样的整数或布尔获得:Ç基础知识,const的无符号字符*为整数或布尔

bool tblexist = false; 
int t_exists = 0;  

tblexist = (bool)sqlite3_column_text(chkStmt, 1); 
t_exists = atoi(sqlite3_column_text(chkStmt, 1)); 

...但没有一个人的作品。从sqlite3_column_text
预期值(chkStmt,1)总是0或1。 但是我得到错误消息:

从 'const的无符号字符*' 到 '为const char *'
初始化参数1无效的转换'int atoi(con​​st char *)'
|| ===构建完成:2个错误,0个警告=== |

如何解决这个问题,并在优雅的方式得到整数或布尔?

+0

将标记从C更改为C++,因为'bool'和'false'是C++特有的。 – 2012-03-21 07:14:04

+0

@JoachimPileborg:如何使用'atoi'? C++? :) – 2012-03-21 07:16:14

+0

@Als不是很“C++” - ish,但仍可以使用。 :) – 2012-03-21 07:24:42

回答

2

第一行,试图转换到bool会总是返回true,因为如果字符串指针不为NULL,它将始终为“true”。如果你想用这个有一对夫妇的方式来处理这个问题:

// 1. Dereference pointer to get first character in string 
tblexist = (*sqlite3_column_text(chkStmt, 1) != '0'); 

// 2. Using string comparison 
tblexist = (strcmp(sqlite3_column_text(chkStmt, 1), "0") != 0); 

对于第二,试试这个:

t_exists = atoi((const char *) sqlite3_column_text(chkStmt, 1)); 

这是因为sqlite3_column_text返回类型const unsigned char *atoi希望const char *

+0

最后通过解引用来解决它。谢谢。 – 2012-03-21 08:07:18

0

atoi或类似的转换将使用昂贵。所有的

const unsigned char _TRUE = '1'; 
const unsigned char* dbDATA = sqlite3_column_text(chkStmt, 1); 
bool exists = (_TRUE == dbDATA[0]); //i assume you are expecting "0" or "1" from DB 
+0

与数据库访问相比昂贵吗? – 2012-03-21 07:26:27

+0

这里是segfault bool bool exists =(_TRUE == dbDATA [0]); – 2012-03-21 07:30:08

0

首先,各列被索引以零开始,因此,除非所述查询请求的两个(或更多)个列,sqlite3_column_text(..., 1)返回第二塔。

其次,该函数返回一个指向字符串,所以你必须取消引用从指针的值,并转换那里的字符串:

const char *data = sqlite3_column_text(chkStmt, 0); 
int val = atoi (data); // for ascii representation of a number 
+0

是的,我需要第二栏的价值。在你的例子的第一行仍然有错误'从'const unsigned char *'无效转换为'const char *''。 – 2012-03-21 07:30:32