Thread: char pointer with for loops

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Oct 2019
    Posts
    11

    char pointer with for loops

    Hi, I need help with this please.
    I am trying to get the function to determine if the second string entered by the user is contained in the first string by defining the substr() function. I was able to achieve it with a while loop and a nested if statement. I was wondering if someone could help me figure out how to do it with a nested for loop. The prototype is given below and i am using eclipse. Thanks!


    Code:
    #include <stdio.h>
    #include <string.h>
    // returns the starting index of the first such occurrence
    // where sub_str was found within str - if one exists
    // otherwise returns -1
    int substr(const char str[], const char sub_str[]);
    int main()
    {
    	char str[255];
    	printf("Enter a string: "); fflush(stdout);
    	scanf("%s", str);
    	char sub_str[255];
    	do
    	{
    		printf("Enter a string to search for (\"quit\" to quit): "); fflush(stdout);
    		scanf("%s", sub_str);
    		if ( strcmp(sub_str, "quit") )
    		{
    			int ind = substr(str, sub_str);
    			if ( ind == -1 )
    			{
    				printf("Not found: %s\n", sub_str);
    			}
    			else
    			{
    				printf("\"%s\" found at starting index %d\n", sub_str, ind);
    			}
    		}
    	} while ( strcmp(sub_str, "quit") );
    	printf("Done!\n");
    	return 0;
    }
    Last edited by bab27; 10-01-2019 at 11:14 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Assigning a char value to char pointer doesn't work.
    By inckka in forum C Programming
    Replies: 5
    Last Post: 03-15-2017, 04:34 AM
  2. Replies: 2
    Last Post: 12-02-2012, 05:25 AM
  3. Read char by char into two-dimensional array pointer.
    By 'Serj Codito in forum C++ Programming
    Replies: 5
    Last Post: 09-08-2012, 09:47 AM
  4. Copy char array to char pointer
    By Suseela in forum C Programming
    Replies: 9
    Last Post: 08-06-2009, 12:49 PM
  5. value of char variable with loops
    By david999 in forum C Programming
    Replies: 5
    Last Post: 11-03-2005, 01:55 PM

Tags for this Thread