Image

Imagedelusory wrote in Imagecprogramming 😴sleepy

Arrays of Structures, Part II

I seem to have figured out what I was doing wrong. However, I still have a couple of unanswered questions:

  1. Input control: How do I stop reading in data from an external file into an array of structures? (Not allowed to use the count method... so it's either trailer or end-of-file. I can't seem to figure out how to do either o_O)
  2. How can I store a "phrase" (two or more words) in one field of a structure? For example, I want the title of Habermann's book (from my previous post), "Operating Systems," to be stored in book[i].title. How do I go about doing that?


Thank you!

UPDATED 02/26/2006 (I know, I'm sloooowwww...)

Solution to #1: I don't know what the hell I was doing wrong... but after fiddling around some more & making some minor changes, I got the input under control using trailer data:

int readlibrary( LIBRARY *b ) {
     int i, j;
     char boundary[] = "STOP";

     j = 0;     /* j counts number of records in library */

     for( i = 0; i < N; i++ ) {
          fscanf( lib, "%s %s %s %d %d", &b[i].author, &b[i].title, &b[i].code, &b[i].hold, &b[i].loan );
          if( strcmp( b[i].author, boundary ) != 0 )
               j++;
          else
               break;
     }

     return j;
}



Solution to #2: In the library.txt file, I contracted two-word book titles with underscores ("_") and wrote a function to remove them:

void convert( char *before, char *after ) {
     char *p;

     /* finds position of the underscore */
     p = strstr( before, "_" );

     if( p != NULL ) {
          /* copies what's after the underscore into 'after' */
          strcpy( after, p + 1 );
          /* concatenates one blank to end of 'after' string */
          strcat( after, " " );
          /* concatenates what is after blank to end of 'after' string */
          strncat( after, before, p - before );

          /* repeat process to put title of book in correct order and */
          /* place the newly formatted title into the original structure */
          p = strstr( after, " " );
          strcpy( before, p + 1 );
          strcat( before, " " );
          strncat( before, after, p - after );
     }
     else /* title of book is only one word long */
          strcpy( after, before );

     return;
}


Then I called this function in printfull():

void printfull( LIBRARY *b, int n ) {
     LIBRARY temp[N];
     int i;

     printf( "AUTHOR\t\tTITLE\t\t\t\tCODE\t#COPY\t#BORR\t#AVAIL\n" );
     for( i = 0; i < n; i++ ) {
          convert( b[i].title, temp[i].title );
          printf( "%-12s \t%-30s \t%-4s \t%-5d \t%-5d \t%-6d \n", b[i].author, b[i].title, b[i].code, b[i].hold, b[i].loan, ( b[i].hold - b[i].loan ) );
     }

     return;
}


*cheers* :D