Im crap at C++. Could someone tell me why this wont work? I checked it over and over and I still can't see the thing I did wrong. It compiles flawlessly, and does everything like I want it to but one feature.
(search() is suppose to tell you whether a substring match exists or not) I want the returned 'int i' to provide information on where the match starts. i.e A successful run would be something like:Code:#include <iostream> #include <cstring> using namespace std; int search(char *str,char *sub); int main() { start: int i; char str[100],sub[100],exit; cout<<"Input data."<<endl; gets(str); cout<<"Input search."<<endl; gets(sub); i=search(str,sub); if(i) cout<<"Match found, starting from the "<<i<<"th letter of your input."<<endl; else cout<<"No match found."<<endl; cout<<"Repeat? y/n"<<endl; do { cin>>exit; if(exit=='y') goto start; } while(exit!='n'); return 0; } int search(char *str,char *sub) { int len=strlen(str),i; char *a,*b; for(i=0;i<len;i++) { a=&str[i]; b=&sub[i]; while(*a==*b) { a++; b++; } if(!*b) return i+1; } return 0; }
Input data.
ifureadthisthenurgay
Input search.
read
Match found, starting from the 4th letter of your input.
Repeat? y/n
But when I entered that exact data it gives me
Input data.
ifureadthisthenurgay
Input search.
read
Match found, starting from the 5th letter of your input.
Repeat? y/n
Thanx in advance



LinkBack URL
About LinkBacks


