c - using strncmp for selection in string -
i new c code. particular code if user inputs name
john,
"john cool" printed. don't think using strncmp() properly. can please help?
#include <stdio.h> #include <string.h> int main(){ char namedata[50], names; int counter = 0, n; printf("enter number of family members being enter program \n"); scanf("%d", &n); (names=0; names<n; ++names) { printf("enter family member name:\n"); scanf("%s",namedata); counter = counter +1; printf("name:"); puts(namedata); } if (strncmp (name,"john") == 0) { printf ("found %s\n",name); } return 0; }
you're facing logical issue here. have 1 array named
char namedata[50] for which, you're taking n inputs, each overwriting previous one. so, last input remain. if want array of "name"s, need use 2d array store names, along line of
char namedata[50][50]; and
scanf("%49s",namedata[names]); and comparison should done in same range loop check each value in array.
that said,
- the usage of
strncpywrong. see man page proper usage. scanf("%s",namedata);potentially unsafe buffer overflow. atleast, usescanf("%49s",namedata);avoid overflow longer inputs.- the recommended signature of
main()int main(void).
Comments
Post a Comment