-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordsCounter.cpp
More file actions
46 lines (40 loc) · 860 Bytes
/
Copy pathwordsCounter.cpp
File metadata and controls
46 lines (40 loc) · 860 Bytes
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
// Programming Challenge 03, chapter 10. This program will count
// the number of words in a string
#include <iostream>
#include <cstring>
using namespace std;
// Function prototype
int words(char *line);
int main()
{
const int SIZE = 80;
char line[SIZE];
int numWords;
// Gets string
cout << "Enter a C-string, 80 or fewer characters: \n";
cin.getline(line, SIZE);
// Count and display number of words
numWords = words(line);
cout << "\nThe number of words in the C-string: " << numWords << "\n" << endl;
return 0;
}
int words(char *line)
{
int words = 0;
int count = 0;
char space = ' ';
if (line == 0)
words = 0;
else
{
while (line[count] != '\0')
{
if (line[count] != space && line[count + 1] == space)
words++;
else if (line[count] != space && line[count + 1] == NULL)
words++;
count++;
}
}
return words;
}