I have to create a program that will read both of these files and print them to the Win32 Console. After it does this, I have to reread the file replacing every fifth word with 10 underscores. My code works correctly for the austin.txt file, but it counts the first five spaces of the cloze.txt file as the first word and replaces the fourth word and then every fifth word after that.
//the libraries used for the program
#include <iostream>
#include <cctype>
#include <string>
#include <fstream>
using namespace std;
int main()
{
const string UNDERSCORES = "__________"; //constant
string fileName; //to be able entered by user
int wordCount = 1; //starting word count
char ch,
previousLetter; //used in printing the file
cout << "Please enter a file name: "; //Prompt user for a file name
cin >> fileName; //input the file name
ifstream inFile;
inFile.open(fileName); //attempt to open the file
while(!inFile) //loop to allow the entry of file name after invalid entry
{
cout << "Error: Not a valid file name. \n" // invalid entry occurs
// message is printed
<< "Please enter a valid file name: "; // reprompt user for file
inFile.clear(); // clears the file
cin >> fileName; // user reenters a file name
inFile.open(fileName); //program opens file
}
cout << "\n~~~~~~~~~~~~~~~~ \n"
<< "ECHOPRINTED TEXT \n"
<< "~~~~~~~~~~~~~~~~ \n" << endl;
inFile.get(ch); //read pointer finds character
cout << ch; //character is printed to screen
while(inFile) //loops to print every character until end of file
{
inFile.get(ch);
cout << ch;
}
cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~ \n"
<< "CLOZE TEST VERSION OF TEXT \n"
<< "~~~~~~~~~~~~~~~~~~~~~~~~~~ \n" << endl;
// reset read pointer to very beginning of file
inFile.clear();
inFile.seekg(0L, ios::beg);
inFile.get(ch);
cout << ch;
while (inFile)
{
previousLetter = ch;
inFile.get(ch);
if((isalpha(ch)) && (!isalpha(previousLetter)))
{
wordCount++;
if(wordCount == 5)
{
cout << UNDERSCORES;
inFile.get(ch);
previousLetter = ch;
while(isalpha(ch) && isalpha(previousLetter))
{
inFile.get(ch);
previousLetter = ch;
}
wordCount = 0;
cout << ch;
}
else
{
cout << ch;
}
}
else
{
cout << ch;
}
}
cout << "\n\n<<< Finished program execution successfully >>>\n\n";
return 0;
}