Hello all. I am new to C++ programming and am having some problems with getting my program to work. The program should report how many words are in a file by only counting characters. I've worked this program over for a day-and-half now, and still cannot get it work correctly. I keep getting 0 for word count. Does anyone see anything wrong in my code?? Thanks....
// This program counts and reports the number of words in a file
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile;
string filename;
char prevChar;
char currChar;
int loopcount;
cout << "Enter the name of the file or \"quit\" to exit: "; // Which file to open?
cin >> filename; // User input
infile.open(filename.c_str()); // Open the file
if (filename == "quit") // If user types "quit"
{
system("pause");
exit(1);
}
if (!infile) // If file is not opened
{
cout << "Unable to open file." << endl;
system("pause");
exit(1);
}
while (infile)
{
loopcount = 0; // Increment counter
infile.get(prevChar); // Primer
infile.get(currChar);
if (currChar == ' ' && prevChar != ' ') // While file is opened
{
loopcount++; // Increment
prevChar = currChar;
infile.get(currChar);
}
cout << "The number of words is: " << loopcount << endl;
// Output to the user with word count
infile.close(); // Close the opened file
infile.clear(); // Clear the error
cout << "Enter the name of the file, or \"quit\" to exit: "; // Do you want to open another file?
cin >> filename; // File name to open
infile.open(filename.c_str()); // Open the file
if (filename == "quit") // If user types "quit"
{
system("pause");
exit(1);
}
if (!infile) // Did the file open?
{
cout << "Unable to open file." << endl;
system("pause");
exit(1);
}
}
system("pause");
}
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
ifstream infile;
string filename;
char prevChar;
char currChar;
int loopcount = 0;
cout << "Enter the name of the file or \"quit\" to exit: "; // Which file to open?
cin >> filename; // User input
infile.open(filename.c_str()); // Open the file
if (filename == "quit") // If user types "quit"
{
//system("pause");
exit(1);
}
if (!infile) // If file is not opened
{
cout << "Unable to open file." << endl;
//system("pause");
exit(1);
}
while (infile)
{
infile.get(prevChar); // Primer
//infile.get(currChar);
if (prevChar == ' ') // While file is opened
{
loopcount++; // Increment
//prevChar = currChar;
}
}
//increment for the last word
loopcount++;
cout << "The number of words is: " << loopcount << endl;
// Output to the user with word count
infile.close(); // Close the opened file
infile.clear(); // Clear the error
system("pause");
}