0

I don't know how to use the find() function to check if a string contains a substring, then the program should print out all Words, and "Contains" if Sentence contains at least one of them. Can anyone help me out? My usage of find() sets A always to true. Thanks for help

#include <iostream>
#include <string>
using namespace std;

string Words, Sentence, buf;
int i, n, j = 0;
string arr[20];
bool A;

int main() {

cout << "Words separated by slashes";
cin >> Words;
cout << "Sentence";
cin >> Sentence;

for (i = 0; i <= Words.length(); i++)
{
if (Words[i] != '/')    
{
    buf = buf + Words[i];
}
else
{  
    arr[n] = buf;
    n = n + 1;
    buf = "";
 } 
 }
 for (j = 0; j <= n; j++)
 { 
 cout << arr[j] << "\n";

 if (Sentence.find(arr[j]) != string::npos)
 {
     A = true;
  }
 }  
 if (A == true)
 {
 cout << "Contains.";
 }
 else
 {
 enter code herecout << "Does not contain.";
  }
 }
5
  • The loop for (i = 0; i <= Words.length(); i++) will go out of bounds of Words. Also remember that e.g. cin >> Sentence will not actually read a sentence, as it stops on space. Commented Sep 10, 2022 at 13:05
  • I see nothing in your code that ever explicitly sets A to false. Commented Sep 10, 2022 at 13:07
  • What's more, you never initialize n so when you first use it, its value will be indeterminate and lead to undefined behavior. And the next loop (for (j = 0; j <= n; j++)) will also go out of bounds. Commented Sep 10, 2022 at 13:07
  • @Someprogrammerdude n is a global and therefore initialised to zero. Commented Sep 10, 2022 at 13:10
  • @john Oh yeah, didn't really notice that. Thanks for pointing it out. Commented Sep 10, 2022 at 13:15

1 Answer 1

1

There are a few bugs and issues in this code I think, but the biggest is the for loops all go too far by one.

for (i = 0; i <= Words.length(); i++)

and

for (j = 0; j <= n; j++)

should be

for (i = 0; i < Words.length(); i++)

and

for (j = 0; j < n; j++)

The valid indexes for a string, vector or array are zero upto but not including the size of the string, vector or array.

This mistake causes the bug that you see. Suppose you have two words in arr, e.g. arr = { "stack", "overflow", "", "", ... } . Because you go around the for loop one too many times you end up searching for arr[2] which equals "". This search always succeeds because every string contains the empty string. And so you always set A to true.

Sign up to request clarification or add additional context in comments.

1 Comment

Words[Words.length()] is valid and defined since C++11. But the second loop is probably the root cause indeed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.