Sektion Angewandte Informationsverarbeitung

Übungen zu Systemnahe Software I, Wintersemester 1996/97

Blatt 4

Beispiellösung zu Aufgabe 6 (20 Punkte)

#include<stdio.h>

#define MAXWORDLEN 16
char c;
char word[MAXWORDLEN] = "";

void fatal_error( char *s )
{
  fprintf( stderr, "Fatal error: %s\n", s );
  exit( 1 );
}

/* read from stdin until the combination star-slash is read.
   beware of star-star-slash and it's likes */
void read_to_comment_end( void )
{
  /* syntactic correct means we need'nt check for EOF
     within a comment. good. :-) */
  while( 1 ){
    if( c == '*' ){
      c = getchar();
      if( c == '/' )
        break;
    }else{
      c = getchar();
    }
  }
  c = getchar();
}

/* read from stdin until the wanted character is read, or
   EOF reached. sounds simple enough ... */
void read_up_to( char wanted )
{
  while( (c != EOF) && (c != wanted) )
    c = getchar();
  c = getchar();
}

/* returns 0 if c is NOT [a-zA-Z0-9_], !=0 else */
int is_word_char( char c )
{
  if( ((c < 'a') || (c > 'z')) &&
      ((c < 'A') || (c > 'Z')) &&
      ((c < '0') || (c > '9')) &&
      ( c != '_' ) ) 
    return 0;
  else
    return 1;
}

/* this procedure reads the next word into "word", discarding any 
   characters that exceed MAXWORDLEN. the word in "word" is then 
   '\0'-terminated. */
void in_word( void )
{
  int ccount = 0;

  if( !is_word_char(c) ) 
    return;
  word[ ccount ] = c; ccount++; c = getchar();
  while( (c != EOF) && is_word_char( c ) ){
    if( ccount < MAXWORDLEN ){
      word[ ccount ] = c; ccount++;
    }
    c = getchar();
  }
  if( ccount < MAXWORDLEN )
    word[ ccount ] = '\0';
  else
    word[ MAXWORDLEN-1 ] = '\0';

  printf( "%s\n", word );
}

#define QUOTE1 '"'
#define QUOTE2 '\''
void out_word( void )
{
  while( c != EOF ){
    if( is_word_char(c) )
      in_word();
    else if( c == QUOTE1 ){
      c = getchar();
      read_up_to( QUOTE1 );
    }else if( c == QUOTE2 )
      c = getchar();
      read_up_to( QUOTE2 );
    }else if( c == '/' ){
      c = getchar();
      if( c == '*' ){
        c = getchar(); 
        read_to_comment_end();
      }
    }else
      c = getchar();
  }
}

int main( void )
{
  c = getchar();
  out_word();
  return 0;
}