Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么string::find()在此代码中不起作用?_String_Find_C++14 - Fatal编程技术网

为什么string::find()在此代码中不起作用?

为什么string::find()在此代码中不起作用?,string,find,c++14,String,Find,C++14,我有一个std::string类型的变量。我想检查它是否包含某个std::字符串。我该怎么做 #include<bits/stdc++.h> using namespace std; int main() { int n; string str; cin >> n; string str1 = "not"; while(n--) { cin >> str; cout <&l

我有一个std::string类型的变量。我想检查它是否包含某个std::字符串。我该怎么做

#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;
}

输出:无输出从输入流读取整数后,应使用
cin.ignore()

cin.ignore()忽略“新行”字符

此外,您不能用
cin>>str读取包含一些空格的行。你应该使用
getline(cin,str)读取一行

您修改的代码:

#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;
}
输出:

NO
NO
YES
YES
YES
NO
YES
可能重复请研究-您的问题与
std::find()
无关。无法重现。您声称“无输出”,但您的代码为
22
7
a
bbbbbbbbbb
not bad
not good
not not not not
NOT
aaaaaanotbbb
NO
NO
YES
YES
YES
NO
YES