سؤال

It's my first time here and I am a beginner at C++. I would like to know how I can split sentences with punctuation mark while I am reading from a text file.

i.e.

hey how are you? The Java is great. Awesome C++ is awesome!

The result would be this in my vector (assuming I have put endl to display each content of the vector):

  • hey how are you?
  • The Java is great.
  • Awesome C++ is awesome!

Here's my code so far:

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;
}

Here is my result:

  • you?
  • great.
  • awesome!

Can you explain why I couldn't get the previous word and fix that?

هل كانت مفيدة؟

المحلول

I will give you a clue. In while statement you have three conditions in the or clause. So if any of them is fulfilled than the while statement do not check other ones. So it takes your first and looks for . (dot). Then after finding it, reads it into the word, so in fact it omits question mark. It looks you need to find other way to solve this. If I were you, I would read whole line and parse it char by char. As far as I am concerned there is no build-in string function that splits words by delimiter.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top