fgets - Why code is being executed in such strange sequence in c? -
int is_valid(char *input) { int i; (i = 0;; i++) { // check null terminator if ( ! input[i]) { printf("stop executing is_valid()"); return 0; } // executed null terminator... o_o printf("%c isdigit: %d\n", input[i], isdigit(input[i])); } return 1; } int main() { char input[80]; fgets(input, sizeof(input), stdin); is_valid(input); return 0; }
output:
1 isdigit: 1 0 isdigit: 1 1 isdigit: 1 isdigit: 0 // why here? null terminator after return?! stop executing is_valid()invalid input!
why null terminator processed via isdigit
before return? and.. ok, why if condition executed after it?
why null terminator processed via
isdigit
before return?
it not. executed '\n'
character read fgets
.
c11-§7.21.7.2
the
fgets
function reads @ 1 less number of characters specifiedn
stream
pointed stream array pointeds
. no additional characters read after new-line character (which retained) or after end-of-file. null character written after last character read array.
for input
101
there 5
characters in there
101\n\0
\n
not digit of course.
you need add condition \n
if (input[i] == '\0' || input[i] == '\n') { printf("stop executing is_valid()"); return 0; }
Comments
Post a Comment