I am working on a homework assignment where I am supposed to read in a data file of the user's choice and count the number of characters, spaces, and lines in the file. I have been able to get both the characters and lines, but I cannot figure out how to get the stream to read the blank spaces between words in the file. Here is my code for the function I am working in as of thus far:
void countFile (ifstream &fp, string &filename, int &charactercount, int &linecount, int &spacecount)
{
//Count Characters
char ch;
while (fp >> ch && fp.eof == false)
{
charactercount++;
}
fp.close();
fp.clear();
fp.open(filename.c_str());
//Count Number of Lines
string nl;
while (!fp.eof())
{
getline(fp, nl);
linecount++;
}
fp.close();
fp.clear();
fp.open(filename.c_str());
//Count Number of blank spaces
char sp;
while (fp >> sp && fp.eof() == false)
{
if (ch == ' ')
{
spacecount++;
}
}
When I run the program, spacecount always comes up as 0 so I believe I am doing something wrong with the while statement used to count spaces perhaps I shouldnt be using fp >>, but I am not sure of what other way to read the data in. Any help would be greatly appreciated
The ASCII table states that a space has the value of 32 (decimal). When you peek at the next character within the file (std::ifstream::peek()), compare the returned character to 32. For example:
You can peek at the next character, or you can extract the next character. The only difference between the two is that std::ifstream::peek() allows you to know the next character before you extract it.
Tried it out but am still coming up with 0 as value for spacecount. My professor mentioned something about using a inf.get command but I am not sure exactly how to use it.
int space_count = 0; // place to hold count
ifstream in("file.txt"); // input file
while(in.good()) // while file is open and reads without error or eof
{
if(32 == in.get()) space_count++; // found space, increment counter
}