Hello i am just beginning how to program and my assignment is to be able to count the number of character, spaces, and words. well my programs counts the characters, spaces and words but when i try to do lines that have leading space or has trailing space it adds a word?? and i can't figure out what it is!!
This is the assignment
Part one reads a file character by character and prints it to the CRT.
Part two: Count the characters you have read; print the count.
Part three: Count only the spaces you have read; print the count.
Part four: Count the words where a word is defined as: a non-space followed by [either a space or EOF] Thus, all of these should count 5 words. ("" is not in the input.)
"Mary had a little lamb."
"Mary had a little lamb." (This line has no trailing space.)
" Mary had a little lamb." (This line has leading space.)
"Mary had a little lamb. "
" Mary had a little lamb. " (This line has trailing space.)
I would change it to this and remove the textFile.get() from the bottom of the loop. It is a lot of redundant code.
1 2 3 4
while( !txtFile.eof() )
{
ch = txtFile.get();
}
Now I will go through your logic and point you in a different direction:
Please note the comment here
1 2
cout<<ch;
cnt_let++; // this is a count of all the characters you read in, not the letters.
If I were to think about you problem I would approach my tracking of information diffeently for example:
You think like this which does not account for the quotes and things that would break words up.
if (isspace(ch ))
I would approach this way because words are only alpha based characters, and I can update my letter count. I would add a string to help track some other information. word is defined as std::string word.
if(isalpha(ch))
{
cnt_let++; // these are the actual letters to count.
word += ch; // I am building the word from the character stream.
}
else
{
// in this else we are everything else. this is where I would count my words
// but I want to make sure I have a word. Like accounting for the other odd characters
// this is non alpha characters. these thoughts account for double spaces and other odd character combinations that would make the file, like the quotes or other thigngs.
cnt_space++;
// this is how I would handle the word breaks, because not every space will be a word break.
// now this is how I use the string. I will check to see if the string has data or not.
if(!word.empty()) // if we are not empty, this will tell me if I have an actual word
{
cnt_word++; // we increment the word count.
// if we wanted to check to see what what the word was we could dump it out.
// we will erase the word so we can build a new one and to account for the other non-alpha characters
word.clear();
}
// we can count the other characters were if we need to like the quotes or not
} // end the else on we are alpha or not.
Tracking the words is what you needed to do and not all of them would be a word break.