Originally Posted by
strugglesWithC
I am a beginner at c. I have been assigned a project that wants a user to enter text from the keyboard and then the number of words is counted.
Before I have written programs that count number of words by counting spaces; however, this program includes spaces and punctuation.
Basically I am having trouble(spent last 6 hours) trying to figure out how to write a loop. A loop that would notice a the first letter or digit and once it hits an element that is not letter or digit would increment a counting variable by 1.
So the loop would run and do something when it hits a letter or number and stop at first element that does is not letter or number.
This would continue til the end of a string.
Any insight would be greatly appreciated!!
The first LETTER or the first letter after a space or punctuation mark, should be where your program increments the word count.
So basically, you have two states to contend with as you "walk" through the string, char by char:
1) your program is OUTSIDE a word. No words get incremented here,
or
2) your program is INSIDE a word, and the word counting variable will be incremented, first thing.
Aside from that algorithmic change, the only difference with your previous program is that you will add the punctuation marks, into the same if() statement that you have used before, for spaces.
Code:
if(char==' ' || char==',' || char=='.' || char=='\n')
type of thing. Add in all the punctuation marks that you need, in the same way.
Use that kind of if statement, inside your while loop, and you're off to a great start.