the program is supposed to read a file specified by the user, and count the number of words. the program is to loop until the user types in 'quit'. The loop and exit functions are working, but my counter is always off by a couple of numbers. I know that my loop is not counting a word if there is no space after it, such as in the end of a file. The professor requires us to do the word count by comparing individual characters and not strings. the example data sets are below.
//***********************************************************
// This program counts the occurrences of "!=" in a data file
//***********************************************************
#include <iostream>
#include <fstream> // For file I/O
usingnamespace std;
int main()
{
int count; // Number of != operators
char prevChar; // Last character read
char currChar; // Character read in this iteration
ifstream inFile; // Data file
inFile.open("myfile.dat"); // Attempt to open file
if ( !inFile )
{ // If file wouldn't open, print message, terminate program
cout << "Can't open input file" << endl;
return 1;
}
count = 0; // Initialize counter
inFile.get(prevChar); // Initialize previous value
inFile.get(currChar); // Initialize current value
while (inFile) // While input succeeds . . .
{
if (currChar == '=' && // Test for !=
prevChar == '!')
count++; // Increment counter
prevChar = currChar; // Update previous value to current
inFile.get(currChar); // Get next value
}
cout << count << " != operators were found." << endl;
return 0;
}
<1> Remove line 40 and 53. Why to you read word into a string? This eats the first word.
<2> your loop-terminating condtition on line 24 condition has problem. As in data1, the last character is '.' (you won't get a white space character into currChar), thus the last word won't be counted. So you should take of 'end of file' condition into account.