打印包含特定单词的行 (C++)

Print the line if it contains a specific word (C++)

我注意到一个用户有类似的问题,但他们是用 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(".....")),这显然不包含在该行中。

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

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

要检查特定单词,如果您想检查单词边界、忽略大小写和标点符号、处理带连字符的单词和其他奇怪的地方,您可能会发现它最容易使用 regular expressions to extract each word, then see if they're in your wordlist. Otherwise, if your wordlist is short you can search for each entry in the line in turn with std::string::find,但是如果wordlist 很长,效率低下,您需要从行中提取候选词。这可以粗略地完成:

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