这是我第一次来,我是C++的初学者。我想知道当我从文本文件中读取文本时如何用标点符号分隔句子。
即
hey how are you? The Java is great. Awesome C++ is awesome!
结果将是我的 vector 中的结果(假设我已放置endl来显示 vector 的每个内容):
到目前为止,这是我的代码:
vector<string> sentenceStorer(string documentOfSentences)
{
ifstream ifs(documentOfSentences.c_str());
string word;
vector<string> sentence;
while ( ifs >> word )
{
char point = word[word.length()-1];
if (point == '.' || point == '?' || point == '!')
{
sentence.push_back(word);
}
}
return sentence;
}
void displayVector (vector<string>& displayV)
{
for(vector<string>::const_iterator i = displayV.begin(); i != displayV.end(); ++i )
{
cout << *i <<endl;
}
}
int main()
{
vector <string> readstop = sentenceStorer("input.txt");
displayVector(readstop);
return 0;
}
这是我的结果:
您能解释一下为什么我无法得到前一个单词并将其修复吗?
最佳答案
我会给你一个线索。在while语句中,or子句中具有三个条件。因此,如果满足while
语句中的任何一个,则不要检查其他语句。因此,这需要您的第一手并寻找。 (点)。然后在找到它之后,将其读入word
,因此实际上它省略了问号。
看来您需要找到其他方法来解决此问题。如果我是你,我会读整行,然后逐个字符地分析它。就我而言,没有内置的字符串函数可以用定界符来分隔单词。