Hello, in our class we are learning about using <fstream> to read from a file, and then separate all of the sentences in it. We must then show the first and last sentence in the file, as well as count the number of words in it. Then we have to make one last decision on what to add to the program (I counted the number of times the letter "a" showed up.)
Everything works, except for showing the last sentence of the text file. Could someone help me identify what the problem is? It just shows up as blank.
(Yes I know my output is messy, I have to make it pretty once I get it to work).
#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
int main()
{
//constants
//variables
ifstream indata;
string paragraph;
string sentence;
string sentence2;
string sentence4;
string word;
int i;
int j;
//open the txt file and display error message if it can't open.
indata.open("paragraph.txt");
if (!indata)
{
cerr << "Error: File cannot be opened." << endl;
return 1;
}
//put the first sentence into a string and show it
getline( indata, sentence, '.' );
cout << "***************************************************************************************************" << endl;
cout << sentence << endl;
//Continue to do each sentence after it, showing each one.
while (!indata.eof() )
{
getline( indata, sentence2, '.' );
cout << "***************************************************************************************************" << endl;
cout << sentence2 << endl;
}
//tell what the first and last sentences are
cout << endl << endl << "'*****" << sentence << "*****' is the first sentence in the article, and '*****" << sentence2 << "*****' is the last sentence in the article." << endl;
//close the file
indata.close();
//reopen the file
indata.open("paragraph.txt");
//count number of words in file
while(!indata.eof())
{
indata >> word;
i++;
}
cout << endl << endl << endl << "The number of words in the file is " << i << endl << endl << endl;
//close the file
indata.close();
//reopen the file
indata.open("paragraph.txt");
//count number of times that "a" is in file
while(!indata.eof())
{
getline( indata, sentence4, 'a' );
j++;
}
cout << endl << endl << "The number of times that the letter 'a' in the file is " << j << endl << endl << endl;
//close the file
indata.close();
return 0;
}
This is more of a guess...
The last sentence is terminated by a period. In this case the extraction operation stops at the period (discarding it) but the end of file is not reached. So the loop starts again, tries to read the content of the stream which is just EOF, sets the eof flag on the stream and sets sentece2 to be an empty string.
There are a number of ways.
You could use another string that temporarily stores the input, and check it for validity. If it's ok you can store in the variable used for the last sentence.
The temp string can be a variable local to the loop, to not clutter the parent scope.