c - The scanf and gets work differently about put '\0' in an array? -
i getting , displaying names, , stop program when type enter key. @ below code correctly result (i know "gets" deprecated):
#include <stdio.h> main() { char name[50]; while(1) { printf("name: "); scanf("%s", name); if(name[0]=='\0') break; else printf("name entered: %s\n", name); } }
but when try use scanf:
printf("nome: "); scanf("%s", nome);
the condition name[0]=='\0'
never true time. why? '\0'
works differently in these functions?
if scanf
cannot assign value variable (because input stream has whitespace, terminating 'string'), doesn't clear out; reason partly not variables have obvious 'clear' state.
so after scanf, nome
still contains whatever contained before. need check if scanf able assign variable instead, testing return value: if (scanf(...) == 1)
- means 'did scanf assign 1 variable?'
Comments
Post a Comment