C: Comparison between character in string and '\0' doesn't work?
I make a function to count the number of characters of the first line of a string. In case the string is only one line long then it counts the number of characters until the terminating null \0. The portion with comparing the ch character to \n works as expected but I can't succeed in comparing the ch character to \0. It never meets the comparison even if I hav开发者_Go百科e added several \0 in the string. Any idea?
#include <stdio.h>
int main() {
/*variables*/
char* string="shit\nand\npee\0";
int bytesRead=0;
int bytesTemp=0;
char ch=' ';
/*find the number of characters before a newline or end of string*/
while(ch!='\n') { //doesn't work with ch!='\0'
sscanf(string+bytesRead, "%c%n", &ch, &bytesTemp);
bytesRead+=bytesTemp;
printf("Bytes read: %d\n", bytesRead);
printf("Variable ch has value: %c\n", ch);
}
return 0;
}
The problem is that you're not testing the return value of sscanf
. If it fails, ch
will not be updated, so you'll get the last symbol twice, then read past the end of the string.
Try with something like:
if (sscanf(string+bytesRead, "%c%n", &ch, &bytesTemp) != 1)
break;
You could also avoid using sscanf
and do the following instead:
while((ch = *string) != '\n' && ch != '\0') {
bytesRead++;
printf("Bytes read: %d\n", bytesRead);
printf("Variable ch has value: %c\n", ch);
string++;
}
This stops when it sees either \n or \0.
精彩评论