【发布时间】: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。