Hi I am trying to make a program that returns a substring of a string if it is found. The cout statement works but the pointer variable inside it prints no contents. I have ran the program with a debugger and the pointer variable definetely has contents.
#include<iostream>
#include<limits>
usingnamespace std;
void pause()
{
cin.clear();
cout<<"Press Enter to Quit: ";
cin.ignore(numeric_limits<streamsize>::max(),'\n');
}
char *createSubString(char *str,char *sub,int len);
int main()
{
char mystr[80];
char *sub;
char mystr2[80];
int len;
cout<<"Enter a String: ";
gets(mystr);
len=strlen(mystr);
cout<<"Enter a substring to search: ";
gets(mystr2);
sub=createSubString(mystr,mystr2,len);
if(sub){
cout<<"Substring Found: "<<sub<<endl; //SUB DOES NOT PRINT OUT
}
else{
cout<<"Substring not Found!"<<endl;
}
pause();
return 0;
}
char *createSubString(char *str,char *sub,int len)
{
char *start;
char *ptr;
char *ptr2;
int count=0;
while(count<len)
{
start=&str[count];
ptr2=start;
ptr=sub;
while(*ptr==*ptr2 && *ptr)
{
ptr2++;
ptr++;
}
//if end of *ptr then above while loop must have found match
//so return the match
if(!*ptr)
{
cout<<ptr<<endl;
return ptr;
}
count++;
}
//return 0 if no substring found
return 0;
}
Thanks for the links. I am doing this exercise just to learn pointers.
Its okay anyhow I just figured out why it was happening. ptr was getting incremented inside the while loop so by the time I returned it it was not the full substring. I had to do this before I returned it.