Is it necessary to implement via loop? You could do this:
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static char *readstring( char *, char ** );
int main( void )
{
char *s1, *s2, *s3;
size_t size1, size2;
if ( ! readstring( "Enter string: ", &s1 ) )
{
fputs( "ERROR: Cannot read string.\n", stderr );
return EXIT_FAILURE;
}
if ( ! readstring( "Enter substring: ", &s2 ) )
{
free( s1 );
fputs( "ERROR: Cannot read substring.\n", stderr );
return EXIT_FAILURE;
}
// strstr() do what you want!
if ( s3 = strstr( s1, s2 ) )
{
size_t index = s3 - s1;
printf( "Found substring at index %zu.\n", index );
}
else
puts( "Substring not found." );
free( s1 );
free( s2 );
return EXIT_SUCCESS;
}
char *readstring( char *prompt, char **sptr )
{
char *p;
size_t size;
// Prints the prompt...
fputs( prompt, stdout );
fflush( stdout );
// Reads a line, dynamically allocating as many memory as necessary.
*sptr = NULL;
size = 0;
if ( getline( sptr, &size, stdin ) == -1 )
return NULL; // returns NULL in case of error.
// Get rid of '\r' or '\n' at the end of the string.
if ( p = strpbrk( *sptr, "\r\n" ) )
*p = '\0';
return *sptr;
}