Count blank spaces in a file

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
closed account (zb0S216C)
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:

1
2
3
4
5
6
7
8
9
10
int main()
{
    const char WHITE_SPACE(32);

    std::ifstream input("File.txt");
    if(input.peek() == WHITE_SPACE)
        // ...

    return(0);
}

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.

Wazzak
Last edited on
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.
you need to declare a temporary character to hold the character from input.get(char&)

1
2
3
4
5
6
7
char c;
while (fin.get(c))
{
    if      (c == '\n')               ++lines;
    else if (isspace(c) && c != '\r') ++spaces;
    else                              ++chars;
}
Last edited on
1
2
3
4
5
6
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
}
Thanks, got it working now
Topic archived. No new replies allowed.