如果包含特定单词,则打印该行(C ++)

时间:2018-04-22 00:04:24

标签: c++ getline

我注意到一个用户有一个类似的问题,但他们是用python编写的,我正试图找出一个c ++解决方案。

我正在编写一个拼写检查程序,如果它包含特定的字符串,我正在尝试从文件中打印该行。我虽然getline()函数对解决方案很有用,但我不太确定如何在我的情况下使用它。

 ifstream inputFileIn(inputFilename);
  list inputFile;
  string word;
  while (inputFileIn >> word)
    {
      transform(word.begin(), word.end(), word.begin(), ::tolower); //convert words to lowercase to spellcheck

      //remove punctuation from the word
      for (int i = 0; i < word.length(); i++)
        {
          if (ispunct(word[i]))
            {
              word.erase(i--, 1);       
            }
        }

      //if spelled incorrectly 
      if (!wordList.contains(word) && std::string::npos == word.find_first_of("0123456789,:;.!?-() ") && word != "\n")
        {
          inputFile.add(word, 0);
        }
    }

因此,如果word在该行中,则会打印出共享该行的所有其他单词。我并不是真的想找人做,但我需要明确一下如何使用getline()

修改

感谢您的回复。我目前正在使用这个

      if (!wordList.contains(word) && std::string::npos == word.find_first_of("0123456789,:;.!?-() ") && word != "\n")
        {
          string line;
          while (getline(inputFileIn, line))
            {
              if (line.find(word))
                {         
                  cout << "Line is: " << line << '\n' << "Word is: " << word << endl;
                }
            }
          inputFile.add(word, 0);
        }
    }

出于某种原因,if (line.find(word))总是返回true,即使我if (line.find("....."))显然没有包含在行中。

1 个答案:

答案 0 :(得分:1)

您确实可以使用getline一次读取一行:

std::string line;
while (std::getline(inputFileIn, line))
{
    ...

要检查特定单词,如果要检查单词边界,忽略大小写和标点符号,处理带连字符的单词和其他奇怪的东西,您可能会发现使用regular expressions提取每个单词最简单,然后看看他们是否在你的单词列表中。否则,如果您的单词列表很短,您可以使用std::string::find依次搜索该行中的每个条目,但如果单词列表很长则效率低下,并且您需要从该行中提取候选单词。这可以粗略地完成:

std::istringstream iss{line};
while (line >> word)
{
    ...transform / remove punctuation etc...
相关问题