linux c/c++ - weird if/else issue
I'm querying a mysql table which then loops through the 开发者_高级运维results.
One of the fields has a value of "0" in it, so when I try the following it doesn't work!
while ((row2 = mysql_fetch_row(resultset2)) != NULL) {
if (row2[2] != "0") {
// the field has a value of 0, but it's still executing the code here!
} else {
// should be executing this code
}
}
I know C/C++ is very strict when it comes variables (unlink php), but I can't figure this one out. Anyone have any ideas why?
You're comparing row2[2]
, a pointer to char
, with a pointer to the constant char
array "0"
.
Use strcmp(row2[2], "0") != 0
(C solution), std::string(row2[2]) != "0"
(C++ solution), or atoi(row2[2]) != 0
if you know row2[2]
is always the string representation of an integer (and cannot be a SQL NULL
value).
You cannot compare string literal like this :
if (row2[2] != "0") //wrong
Either you do this :
if (strcmp(row2[2], "0")) //correct
Or this:
if (std::string(row2[2]) != "0") //correct
For this particular case, when there is only one character you can also do this:
if (row2[2][0] != '0') //correct - not the single quote around 0!
精彩评论