-
Notifications
You must be signed in to change notification settings - Fork 1
/
ex.10.3.c
99 lines (85 loc) · 1.73 KB
/
ex.10.3.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
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <stdio.h>
#include <stdbool.h>
bool alphabetic (const char c)
{
return ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') );
}
bool numeric (const char c)
{
return ( c >= '0' && c <= '9' );
}
void readLine (char buffer[])
{
char character;
int i = 0;
do
{
character = getchar ();
buffer[i] = character;
++i;
}
while ( character != '\n' );
buffer[i - 1] = '\0';
}
int countWords (const char string[])
{
int i, wordCount = 0;
bool inWord = false, inNumber = false;
bool alphabetic (const char c), numeric (const char c);
for ( i = 0; string[i] != '\0'; ++i ) {
if ( alphabetic(string[i]) ) {
if ( !inWord && !inNumber ) {
++wordCount;
inWord = true;
} else if ( inNumber ) {
--wordCount;
inNumber = false;
}
} else if ( string[i] == '\'' ) {
if ( inNumber ) {
inNumber = false;
}
} else if ( numeric(string[i]) ) {
if ( !inWord && !inNumber ) {
++wordCount;
inNumber = true;
} else if ( inWord ) {
--wordCount;
inWord = false;
}
} else if ( string[i] == ',' || string[i] == '.' ) {
if ( inWord ) {
inWord = false;
}
} else if ( string[i] == '-' ) {
if ( inNumber ) {
--wordCount;
inNumber = false;
}
} else {
inWord = false;
inNumber = false;
}
}
return wordCount;
}
int main (void)
{
char text[81];
int totalWords = 0;
int countWords (const char string[]);
void readLine (char buffer[]);
bool endOfText = false;
printf ("Type in your text.\n");
printf ("When you are done, press 'RETURN'.\n\n");
while ( ! endOfText )
{
readLine (text);
if ( text[0] == '\0' )
endOfText = true;
else
totalWords += countWords (text);
}
printf ("\nThere are %i words in the above text.\n", totalWords);
return 0;
}