Q. Enter and store n number of strings and then search for a particular string.
I am able to enter the 'Number of strings' and then I am also able to enter the strings. But then the strings don't get printed. Neither the comparison and searching takes place, and it shows a segmentation error. This happens when I use gets() for the input of strings. But when I use scanf() for strings input, the program terminates right after I enter 'Number of strings'. Why so?
Here's the code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[200],names[100];
int n,i;
int flag=0;
printf("Give number of strings:\n");
scanf("%d",&n);
printf("Enter the strings:\n");
for(i=0;i<n;i++)
{
gets(names);
}
printf("Entered Values are:\n");
for(i=0;i<n;i++)
{
printf("%s\t",names[i]);
}
printf("Enter the string you want to search for:\n");
scanf("%s",str);
for(i=0;i<n;i++)
{
if(strcmp(names[i],str) == 0)
{
flag=1;
break;
}
}
if(flag==1)
printf("Yes this string %s exists!\n",str);
else
printf("No it does not exists");
return 0;
}