Solution to the getword Problem
/*
* A Solution to the Warm-up Exercise
*/
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int getword(char *word, int n)
{
int c;
char *w = word;
assert(n >= 2);
while (isspace(c = fgetc(stdin)) && c != '\n')
;
if (c != EOF)
*w++ = c;
if (!isalpha(c))
{
*w = '\0';
return c;
}
while (isalnum(c = fgetc(stdin)))
if (n > 0)
{
*w++ = c;
--n;
}
ungetc(c, stdin);
*w = '\0';
return *word;
}
#define MAXLEN 10
int length[MAXLEN] = { 0 };
int main()
{
int i, n;
int lines = 0;
char word[MAXLEN];
while (getword(word, MAXLEN) != EOF)
if (isalpha(word[0]))
{
n = (n = strlen(word)) < MAXLEN ? n - 1 : MAXLEN - 1;
++length[n];
}
for (i = 0; i < MAXLEN; ++i)
printf("%d words of length %d%s\n", length[i],
i + 1, i < MAXLEN - 1 ? "" : " or more");
return 0;
}
Back to Courses.
Back to C++ and OOP.
Back to the Pretest.
Home |
Courses |
Tools |
Resources
Clients |
Successes |
Contact |
Site Map |
Links |
About Us
All text and images on this website are Copyright © 2001-2003 BD Software. All rights reserved.
|
 |