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 specified n stream pointed stream array pointed s. 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

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -