我想创建一个函数来搜索从cin getline为多个单词保存的字符串。我已经找到了一个例子,我将在下面给出如何只搜索一个单词。
#include <string>
#include <iostream>
using namespace std;
int main()
{
string sentence = "My scanner is not working.";
cout << "sentence: " << sentence << endl;
string search;
size_t pos;
search = "printer";
pos = sentence.find(search);
if (pos != string::npos)
cout << "sentence contains " << search << endl;
else
cout << "sentence does not contain " << search << endl;
search = "scanner";
pos = sentence.find(search);
if (pos != string::npos)
cout << "sentence contains " << search << endl;
else
cout << "sentence does not contain " << search << endl;
return 0;
}
我如何搜索多个单词??
答案 0 :(得分:-1)
如何使用循环?
#include <string>
#include <iostream>
using namespace std;
int main()
{
string sentence = "My scanner is not working.";
cout << "sentence: " << sentence << endl;
string search[] =
{ "printer", "scanner", "working" };
for (size_t i = 0; i < sizeof(search) / sizeof(search[0]); i++)
{
size_t pos = sentence.find(search[i]);
if (pos != string::npos)
cout << "sentence contains " << search[i] << endl;
else
cout << "sentence does not contain " << search[i] << endl;
}
return 0;
}