By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,082 Members | 2,135 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,082 IT Pros & Developers. It's quick & easy.

Pattern matching

P: 21
I write this program for pattern-matching,but it gives wrong result:
Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<conio.h>
  3. #include<string.h>
  4. using namespace std;
  5. main()
  6. {
  7.     char text[100],pat[10];
  8.     cout<<"text:";cin>>text;
  9.     cout<<" pattern:";cin>>pat;
  10.     int pos=0,i=0,j=0;
  11.     while((i<=strlen(pat))&&(j<=strlen(text)))
  12.     {
  13.         if(pat[i]==text[j])
  14.         {
  15.             i++;
  16.             j++;
  17.         }
  18.         else
  19.         {
  20.             pos++;
  21.             j=pos;
  22.             i=0;
  23.         }
  24.  
  25.     }
  26.     if(i>strlen(pat))
  27.         cout<<"Matching occurs from"<<pos+1;
  28.     else
  29.         cout<<"No matching ";
  30. }
  31.  
For example,I enter
text:asm
pattern:a
result:No matching!
I think the algo is right,but why it gives such wrong result??
Jun 9 '07 #1
Share this Question
Share on Google+
1 Reply


Expert 10K+
P: 11,448
I write this program for pattern-matching,but it gives wrong result:
Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<conio.h>
  3. #include<string.h>
  4. using namespace std;
  5. main()
  6. {
  7.     char text[100],pat[10];
  8.     cout<<"text:";cin>>text;
  9.     cout<<" pattern:";cin>>pat;
  10.     int pos=0,i=0,j=0;
  11.     while((i<=strlen(pat))&&(j<=strlen(text)))
  12.     {
  13.         if(pat[i]==text[j])
  14.         {
  15.             i++;
  16.             j++;
  17.         }
  18.         else
  19.         {
  20.             pos++;
  21.             j=pos;
  22.             i=0;
  23.         }
  24.  
  25.     }
  26.     if(i>strlen(pat))
  27.         cout<<"Matching occurs from"<<pos+1;
  28.     else
  29.         cout<<"No matching ";
  30. }
  31.  
For example,I enter
text:asm
pattern:a
result:No matching!
I think the algo is right,but why it gives such wrong result??
Congratulations for hitting that (in)famous OBOE (Off By One Error). Check the
conditions in the while clause: change both '<=' to '<' and you're in busyness.
Also adjust the condition in that last if clause accordingly.

kind regards,

Jos (<--- been bitten by the OBOE too many times ;-)
Jun 9 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.