comp.lang.c
[Top] [All Lists]

Re: taking a "word" as input

Subject: Re: taking a "word" as input
From: arnuld
Date: Wed, 30 Apr 2008 22:20:23 +0500
Newsgroups: comp.lang.c

> On Wed, 30 Apr 2008 20:54:48 +0500, arnuld wrote:

> by accident, it is actually exercise 6-4 of K&R2 :)


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() ) )
    {
      ;
    }

  while( --max_length )
    {
      if( isalpha( c ) )
        {
          *w++ = c;
        }
      else if( c == '\n' || c == EOF || isspace( c ) )
        {
          *w = '\0';
          break;
        }
      else
        {
          return 0;
        }

      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. 

     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';
    }

    

  return word[0];
}


========== OUTPUT ============
Welcome to the Emacs shell

/home/arnuld/programs/C $ gcc -ansi -pedantic -Wall -Wextra getword.c 
/home/arnuld/programs/C $ ./a.out 
like this
like
/home/arnuld/programs/C $ ./a.out 
like3
/home/arnuld/programs/C $ ./a.out 
9like
/home/arnuld/programs/C $ ./a.out 
         like   ll
like
/home/arnuld/programs/C $ 



-- 
http://lispmachine.wordpress.com/
my email ID is @ the above address


<Prev in Thread] Current Thread [Next in Thread>
Privacy Policy