如何检查数组的元素是否在文件中

时间:2015-02-13 23:09:08

标签: c++ arrays string

如果从输入文件中找到单词“the”,“an”或“a”,我的任务是添加一个形容词。我想知道是否有一种更优雅的方式来编写这段代码,而不是大量的if语句和一堆或者一样。

我的想法是在数组中存储“the”,“an”和“a”。我想要做的是检查输入文件是否存在任何这些文章。

我使用的if语句没有实现这一点。对不起,我是新人。

   //Run in Command Line
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>


using namespace std;
int main (int argc,char *argv[])
{
string fileName;
ifstream inputFile;
string adjective;

cout << argc <<endl; //sees whether the correct number of arguments are being passed through
cout << argv[0] <<endl; //checks that
cout << argv[1] <<endl;   //the correct arguments
cout << argv[2] <<endl;     //are being passed through
if (argc == 3)
{
    adjective = argv[1];
    inputFile.open(argv[2], ios::in);
}
else
{
    cout<< "File not found." <<endl;
    exit(1);
}
//------------------------------------------------------------//


char firstLetter = adjective[0];
string index = " ";
string ArticleThe[] = {"THE", "THe", "The",
                       "tHE", "thE", "tHe",
                       "ThE", "the"};
string ArticleA[] = {"A", "a"};
string articleAn[] = {"AN", "An", "aN", "an"};


while (!inputFile.eof()) //while not at the end of file
{
    inputFile >> index; //traverse through string

    {
        if (articleThe.find(index) != articleThe.end())
        {
            inputFile >> index; //if article 'the' is found, move to noun
            if (!inputFile.eof())
            {
                //display memo with adjective added after all "the" articles
            }
        }

        else if (articleA.find(index) != articleA.end() && adjective.isVowel(firsLetter) == 1)
        {
            inputFile >> index;
             if (!inputFile.eof())
            {
                //display memo with adjective added after all "a" articles
            }
        }
        else if (articleAn.find(index) != articleAn.end() && adjective.isVowel(firsLetter) != 1)
        {
            inputFile >> index;
             if (!inputFile.eof())
            {
                //display memo with adjective added after all "an" articles
            }
        }
    }





}



}

bool isVowel(char firstLetter)
{
    if (firstLetter == 'a'
    || firstLetter == 'e'
    || firstLetter == 'i'
    || firstLetter == 'o'
    || firstLetter == 'u'
    || firstLetter == 'A'
    || firstLetter == 'E'
    || firstLetter == 'I'
    || firstLetter == 'o'
    || firstLetter == 'u')
    return true;

else
    return false;
}

1 个答案:

答案 0 :(得分:0)

您可以简单地使用regex而不是自己编写状态机:

regex re("(^|[^_[:alnum:]])(the|a)($|[^_[:alnum:]])", regex_constants::icase);

if(regex_search("the test", re))
    cout << "#1 matches!\n";

if(regex_search("A TEST", re))
    cout << "#2 matches!\n";

if(regex_search("wat?", re))
    cout << "#3 matches!\n";

Shows that #1 and #2 match