扫描数组中声明的字符串的用户输入

时间:2017-09-12 06:34:48

标签: c++ arrays

我正在创建一个程序,用于扫描用户输入以查找数组中列出的单词。 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;
}

2 个答案:

答案 0 :(得分:1)

为了使find能够正常工作,你应该使用像这样的迭代器

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/

答案 1 :(得分:0)

find函数会发现negvibe数组的某些元素等于userfeeling。如果您要检查negvibe的任何元素是否为userfeeling的子字符串,则应循环遍历negvibe并使用std::string::find方法。

bool found_negvibe = false;
for (int i = 0; i < sizeof(negvibe) / sizeof(*negvibe); i++) {
    found_negvibe = found_negvibe || userfeeling.find(negvibe[i]) != string::npos;
}

另外,您不需要指定negvibe数组的大小,您可以这样写:

string negvibe[] = {"bad","terrible","lousy","meh"};

还有一件事,你可能更喜欢在数组上使用std::vector,只是因为c ++用于获取向量大小的能力比获得数据的要简单得多。数组的大小。

vector negvibe = {"bad","terrible","lousy","meh"};

bool found_negvibe = false;
for (int i = 0; i < negvibe.size(); i++) {
    found_negvibe = found_negvibe || userfeeling.find(negvibe[i]) != string::npos;
}