-1

I have a variable of type std::string. I want to check if it contains a certain std::string. How would I do that?

#include<bits/stdc++.h>
using namespace std;

 int main()
 {
     int n;
     string str;
     cin >> n;
    string str1 = "not";
    while(n--)
   {
     cin >> str;
       cout << "2";
    if(str.size() >= str1.size())
    {
      if (str.find(str1) != string::npos) 
      {
        cout << "1";
      } 
     else
        cout << "2";
    }   

  }
    return 0;
}

Input:

      2
      i do not have any fancy quotes
      when nothing goes right go left

output: no output

James Z
  • 12,209
  • 10
  • 24
  • 44
Khushal Vyas
  • 316
  • 3
  • 8
  • Possible duplicate of [How to read a complete line from the user using cin?](https://stackoverflow.com/questions/5455802/how-to-read-a-complete-line-from-the-user-using-cin) – Ken Y-N Jan 11 '19 at 06:38
  • Please study [how to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) - your problem has nothing to do with `std::find()`. – Ken Y-N Jan 11 '19 at 06:40
  • Can't reproduce. You claim "no output", but your code [does in fact produce output](https://rextester.com/NVGSDI12500) of `22` – Igor Tandetnik Jan 11 '19 at 15:34

1 Answers1

0

After reading an integer from the input stream, you should use cin.ignore(); before reading any strings from the input stream.

cin.ignore(); ignores the "new line" character.

Also, you can not read a line which contains some spaces with cin >> str;. You should use getline(cin, str); to read a line.

Your modified code:

#include<bits/stdc++.h>
using namespace std;

int main() {
  int n;
  string str;
  cin >> n;
  cin.ignore();
  string str1 = "not";
  while (n--) {
    getline(cin, str);
    if (str.find(str1) != string::npos) 
      cout << "YES" << endl;
    else
      cout << "NO" << endl;
  }
  return 0;
}

Input:

7
a
bbbbbbbbbb
not bad
not good
not not not not
NOT
aaaaaanotbbb

Output:

NO
NO
YES
YES
YES
NO
YES