-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcounting_words_in_a_line.c
86 lines (66 loc) · 1.35 KB
/
counting_words_in_a_line.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Count number of words in a line.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#define LINE_LEN 100
int count(const char * const s);
bool acceptable_char(int ch);
bool ignore_ch(int ch);
int main(void)
{
char words[LINE_LEN+1]= {'\0'};
int words_count=0;
do
{
printf("Enter a line(just enter to exit):");
char * wo = NULL;
wo = fgets(words,LINE_LEN-1,stdin);
if(wo == NULL)
{
fprintf(stderr,"fgets failed.\n");
exit (EXIT_FAILURE);
}
//printf("words:%s\n",words);
words_count=count(words);
printf("Words count is: %d\n\n",words_count);
}
while(words[0]!='\n');
printf("Finished.\n");
return EXIT_SUCCESS;
}
int count(const char * const s)
{
unsigned idx=1;
int cnt;
if(ignore_ch(s[0]) )
cnt=0;
else
{
for(cnt=0; s[idx]!='\0'; idx++)
{
if(isspace(s[idx]) && acceptable_char(s[idx-1]))
cnt++;
}
}
return cnt;
}
bool acceptable_char(int ch)
{
bool r;
if(isalpha(ch) || isdigit(ch))// isalnum
r=true;
else
r=false;
return r;
}
bool ignore_ch(int ch)
{
bool r;
if(ch=='\0' || ch=='\n' || ch==EOF)
r=true;
else
r=false;
return r;
}