Home > front end >  Why isn't my brute-force string match algorithm display an output?
Why isn't my brute-force string match algorithm display an output?

Time:02-28

Here is the source code of the bfSM algorithm. The program should display the starting index of the part where a total match with the pattern is found, or -1 if there are no matches in the given text. I tried including all the libraries i've used thus far while programming but when I debug the program nothing is displayed on the console except for "(process 15936) exited with code 0". I'm not sure what exactly am I missing here an would appreciate some help.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include<stdio.h>
#include<string.h>
using namespace std;

int bruteForceSM(string p, string t) {
    for (int i = 0; i < (t.size() - p.size()); i  ) {
        int j = 0;
        while(j < p.size() && p[j] == t[i   j]) { j  ; }
        if (j == p.size()) { return i; }
    }
    return -1;
}

int main(){
    string text = "sally sells seashells by the seashore";
    string pattern = "shell";
    bruteForceSM(pattern, text);
    return 0;
}

CodePudding user response:

You never print the result, which is the reason you cannot see any result. In the main function, replace

bruteForceSM(pattern, text);

with

cout << "Index at which pattern is found: " << bruteForceSM(pattern, text) << endl;

This will print

Index at which pattern is found: 15

As an additional general advice: never use using namespace std; (see Why is "using namespace std;" considered bad practice? for more information on why).

  • Related