【问题标题】:Print the line if it contains a specific word (C++)如果包含特定单词,则打印该行(C++)
【发布时间】:2018-04-22 00:04:23
【问题描述】:

我注意到一个用户有类似的问题,但他们是用 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获取字符串,然后使用find

标签: c++ getline


【解决方案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...

【讨论】:

  • 感谢您的回复。我使用了那个while循环和find(),但由于某种原因,if语句总是返回true。我已经用这个问题更新了 OG 帖子。
  • 您应该已经阅读了链接的文档和 find 的示例;-P。它不返回布尔值,而是返回找到子字符串的字符串的偏移量,或者如果未找到子字符串,则返回特殊的标记值npos(“无位置”)。您的 if 需要检查 find 不返回 npos
猜你喜欢
  • 2016-02-12
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-15
  • 1970-01-01
相关资源
最近更新 更多