L-6 MCS 275 Mon 22 Jan 2001
Below is the listing for the program we discussed in class.
/* MCS 275 L-6 Mon 22 Jan 2001 : counting and storing words on line */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define MAXLEN 80 /* maximum #characters in string */
int read_line (char s[]);
/* Reads a line of characters (until user hits enter).
The string read is in "s" and the function returns the number
"n" of characters in the string, i.e.: s[n] == '\0' (See L-5) */
int count_words (char s[]);
/* returns the number of words on the line */
int words_count (char s[]);
/* returns the number of words on a line, without using "isspace()" */
int store_words (char s[], char *w[]);
/* stores the words in the string s in w, the integer on return is
the number of words in w */
int main()
{
char line[MAXLEN];
char* words[MAXLEN];
int i,n,m;
printf("Give a line (< %d characters) : ", MAXLEN);
n = read_line(line);
printf("Your line is :\n \"%s\" \n", line);
m = count_words(line);
printf("There are %d characters and %d words on this line\n", n,m);
m = words_count(line);
printf("The second word count : %d\n",m);
m = store_words(line,words);
printf("The words on the line are :\n");
for (i=0; i < m; i++)
printf(" %s\n",words[i]);
printf("The words in backward order on the line:\n");
for (i=m-1; i>=0; i--)
printf("%s ", words[i]);
printf("\n");
return 0;
}
int read_line (char s[])
{
int c,i;
for (i=0; (c=getchar()) != EOF && c != '\n' && i < MAXLEN; ++i)
s[i] = c;
s[i] = '\0';
return i;
}
int count_words (char s[]) /* count words with "isspace()" */
{
int i=0;
int cnt=0;
while (s[i] != '\0')
{
while (isspace(s[i])) ++i; /* skip spaces */
if (s[i] != '\0')
{
++cnt; /* found new word */
while (!isspace(s[i]) && s[i] != '\0') ++i; /* skip word */
}
}
return cnt;
}
int words_count (char s[]) /* count words without "isspace()" */
{
int i=0;
int cnt=0;
while (s[i] != '\0')
{
while (s[i] == ' ') ++i; /* skip spaces */
if (s[i] != '\0')
{
++cnt; /* found new word */
while ((s[i] != ' ') && s[i] != '\0') ++i; /* skip word */
}
}
return cnt;
}
int store_words (char s[], char *w[])
{
int i=0;
int cnt=0;
int ind;
while (s[i] != '\0')
{
while (s[i] == ' ') ++i; /* skip spaces */
if (s[i] != '\0')
{
w[cnt] = calloc(MAXLEN,sizeof(char)); /* store word */
ind = 0;
while ((s[i] != ' ') && s[i] != '\0')
w[cnt][ind++] = s[i++];
w[cnt][ind] = '\0';
++cnt; /* augment counter */
}
}
return cnt;
}