I have done a program where input given should be stream of characters and program counts the
non-whitespace characters and words. word is defined as the stream of characters which are separated by a whitespace character. so here is the program..
#include <stdio.h>
#include<ctype.h>
#include <stdbool.h>
#include<iso646.h>
int main(void)
{ unsigned long int wordcount = 0,charcount = 0, count=1;
int ch;
bool flag, prev;
while ((ch = getchar()) != EOF)
{ if(isgraph(ch))
flag=true;
else
flag=false;
if(flag)
charcount++;
if(count ==1)
prev = flag;
if(count != 1)
{ if(prev and (not flag))
wordcount++;
prev = flag;
}
count++;
}
if((ch == EOF) and flag)
wordcount++;
printf("\nnumber of words counted are %lu \n", wordcount);
printf("\nnumber of characters counted are %lu \n", charcount);
return 0;
}
now I have checked this program on simple sentences. But just for practice, I want to do
detailed software testing on this. So how can I do that ? Do I just give more number of sentences ? I tried to give few paragraphs from some novels I found at project gutenberg.
what else I can do here ? Also can I improve the efficiency of this program ?
There are various basic tests to do:
And so it goes on…this is boundary testing; making sure that the code works correctly on boundary conditions.
Your assignment of the value from
getchar()to anunsigned long int(now fixed in the question) is unusual. Since the return value is positive for a regular character and negative (EOF) for end-of-file or error, it is normal to assign it to a signed plainint.Your test
ch == EOFafter the loop is redundant; the only way out of the loop is when the condition is true.Using
<iso646.h>and the (macros) keywordsandandnotis unusual too.Most commonly, people do not put code on the same line as the open brace of a block.
You could increment
charcountin theifblock where you setflag = true;. You could use anelseblock instead ofif (count != 1). In fact, AFAICT, your code:could be written as:
The description ‘number of characters counted’ isn’t strictly accurate; it is the number of graphical (non-blank, non-control) characters that you’re reporting. That’s probably on the hyper-nitpicking end of the fussiness scale, though (along with the observation that the ‘number of words’ is a singular quantity and it should be ‘is’ rather than ‘are’).
It is slightly unusual to start your
countat 1 rather than zero. It seems to record ‘one more than the number of raw characters read into the program’, which is an unusual quantity to record. More normally, you’d initialize it to 0 too, and modify the test I rewrote to read:(You can use
count != 0orcount > 0; for an unsigned value, the terms are equivalent.)You might be able to simplify your conditionals by initializing
prevappropriately (probably tofalse).