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,

  1. the usage of strncpy wrong. see man page proper usage.
  2. scanf("%s",namedata); potentially unsafe buffer overflow. atleast, use scanf("%49s",namedata); avoid overflow longer inputs.
  3. the recommended signature of main() int main(void).

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -