The first loop discards all but the last line.
You want the last two loops to be under the first.
Your match logic is reversed. You want to set p
to 1 before the inner loop and set it to 0 if the chars do not match.
Your for
loop for i
must stop short of k
. It should be k - l
to allow it to not go beyond the end of the x
string.
You have the wrong index when scanning x
. It should be i + j
And, you want to stop reading lines on a match.
Here's some refactored code:
#include <string>
#include <iostream>
using namespace std;
int
main()
{
int n,
p = 0;
string x,
y = "yes";
int l = y.size();
// get number of input lines
cin >> n;
// read in all possible input lines
for (int i = 0; i < n; i++) {
// get next input line
cin >> x;
// show it
cout << "Input: " << x << endl;
// get the length of the string/line
int k = x.size();
// loop through all possible starting points for the substring in the
// line buffer
// NOTE: we must stop early based on the length of the string we're
// searching for (hence, the "k - l")
for (int i = 0; i < (k - l); i++) {
// say we [might] have a match
p = 1;
// loop through chars and stop early if we any corresponding char
// that does _not_ match
for (int j = 0; j < l; j++) {
if (x[i + j] != y[j]) {
p = 0;
break;
}
}
// print a match and stop
if (p) {
cout << "Match: " << x << endl;
break;
}
}
// stop reading when the line matches
if (p)
break;
}
}
Here is the program output:
Input: noway
Input: ofcourseyousilly
Input: thisisthegayestquestion
Match: thisisthegayestquestion