2

I made following two codes for searching string s2 in string s1 and if s2 is found in s1 then the address of location where match is found is printed and s1 should be printed from location of match to last character of s1. if s1="god is great" and s2="is" then address of match as well "is great" should be printed.

CODE 1:
#include<stdio.h>
#include<string.h>

void main()
{
    char s1[80]="god is great",s2[10]="is";
    char *searchptr;
    searchptr=strstr(s1,s2);
    printf("%p\n%p\n",searchptr,s1);
    sprintf(s1,"%s",searchptr);
    puts(s1);
}

CODE 2:
#include<stdio.h>
#include<string.h>

void main()
{
    char s1[80],s2[10];
    char *aptr;
    printf("%s\n%s\n","enter a line","enter string to be searched");
    fgets(s1,80,stdin);
    printf("\n");
    fgets(s2,10,stdin);
    aptr=strstr(s1,s2);
    printf("%p\n,aptr);
    sprintf(s1,"%s",aptr);
    puts(s1);
}

In first code i have already initialized the string and its working but the second code is giving really unexpected result. It is giving the address of matching in every case(as i have tried) aptr=0000000 .is there anything wrong in using fgets as in second code i want to take input from keyboard?

Algo
  • 841
  • 1
  • 14
  • 26
Amit Bisht
  • 131
  • 3

1 Answers1

5

fgets stores the '\n' - newline (entered when enter key is pressed) in the read buffer as well. So your search string s2 becomes "is\n" which is not present in the s1 to aptr is NULL and that is being printed.

You need to trim the '\n' from s2, you can do that by

fgets(s2,10,stdin);
if(s2[strlen(s2)-1] == '\n')
   s2[strlen(s2)-1] = '\0';

Also, check for aptr not NULL before printing it.

Rohan
  • 52,392
  • 12
  • 90
  • 87