我正在创建一个程序,用于扫描用户输入的数组中列出的单词。 find()
函数似乎可以工作,但我找不到任何说明如何为我想做的事情实现它的信息。我对编程还很陌生(很明显)。
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string subj [5]={"I","He","She","We","They"};
string verb [5]={" like"," hate"," sacrifice"," smell"," eat"};
string obj [5]={" bacon","s cats","s bagels","s children","s cops"};
string greeting [5]={"How are you","How's it going","Sup dude","Hey","Hello"};
string negvibe [4]={"bad","terrible","lousy","meh"};
string userfeeling;
int main()
{
srand(time(0));
int rando = rand() %5;//generates a random number between 0 and 4
int rando1 = rand() %5;
int rando2 = rand() %5;
cout << greeting [rando1] << "." << endl;
getline(std::cin,userfeeling);
if .... // What has to be done here?
find(negvibe, negvibe + 4, userfeeling) != negvibe + 4);
// Something like that?
// then ...
{
cout << subj[rando] << verb[rando1] << obj[rando2] <<"." <<endl;
}
return 0;
}
最佳答案
为了使查找正常工作,您应该像这样使用迭代器
if(find(std::begin(negvibe), std::end(negvibe), userfeeling) != std::end(negvibe)){
//code you want to happen if your word is found
}
同样在您当前的代码中,if 语句实际上没有做任何事情,因为您以分号而不是 {} 结束它,或者如果它是一行则将其留空。您也可以看到 if 语句的示例
下面是查找和迭代器的链接 http://www.cplusplus.com/reference/algorithm/find/
关于c++ - 扫描用户输入以查找数组中声明的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46169478/