|
|
arnuld <NoSpam@xxxxxxxxxx> writes:
>> On Wed, 30 Apr 2008 20:54:48 +0500, arnuld wrote:
>
>> by accident, it is actually exercise 6-4 of K&R2 :)
I don't have K&R2 so I don't know the end point of this exercise, so I
may have this wrong...
> How about this code. It works fine:
>
> /* A program that takes a single word as input. It will discard
> * the whole input if it contains anything other than the 26 alphabets
> * of English. If the input word contains more than 30 letters then only
> * the extra letters will be discarded . For general purpose usage of
> * English it does not make any sense to use a word larger than this size.
> * Nearly every general purpose word can be expressed in a word with less
> * than or equal to 30 letters.
> *
> * version 1.1
> *
> */
>
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <ctype.h>
>
>
> enum MAXSIZE { WORDSIZE = 30 };
>
> int getword( char *, int );
>
>
> int main( void )
> {
> char ac[WORDSIZE];
>
> if( getword( ac, WORDSIZE ) )
> {
> printf("%s\n", ac);
> }
>
> return EXIT_SUCCESS;
>
> }
>
>
> int getword( char *word, int max_length )
> {
> int c;
> char *w = word;
>
>
> while( isspace( c = getchar() ) )
> {
> ;
> }
I find { ; } a messy way of saying nothing, but that is a style
point. More important, if this will be used to read more than one
word (eventually) you need to skip anything that you don't count as a
word character, not just spaces.
> while( --max_length )
> {
> if( isalpha( c ) )
> {
> *w++ = c;
> }
> else if( c == '\n' || c == EOF || isspace( c ) )
> {
> *w = '\0';
> break;
> }
> else
> {
> return 0;
When the word ends because of this condition, why do you return 0
rather than the word you have read? You do have a word to return.
> }
>
> c = getchar();
> }
>
> /* I can simply ignore the if condition and directly write the '\0'
> onto the last element because in worst case it will only rewrite
> the '\n' that is put in there by else if clause.
I think the comment is confusing. Without the if below, you re-write
a 0 that is already there. A \n is never put into the buffer.
> or in else if clause, I could replace break with return word[0].
>
> I thought these 2 ideas will be either inefficient or
> a bad programming practice, so I did not do it.
> */
> if( *w != '\0' )
> {
> *w = '\0';
> }
I'd just write *w = '\0';
> return word[0];
That's a char. Given what you said about conversions and clarity, you
should really write return word[0] != '\0'; or maybe return !!word[0];
> }
--
Ben.
|
|