creating arrays

in desperate need of help

Page 1 of 1

3 Replies - 1920 Views - Last Post: 16 January 2009 - 03:33 PM Rate Topic: -----

#1 casper93   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 11-January 09

creating arrays

Posted 15 January 2009 - 07:15 PM

I need first_name and last_name and all the other nessary information in my program to be in arrays and the number that is in the brackets is i ( for eg array[i]) because that variable increases by one every time it goes back to the menu. I really want all the information to be saved so i can display it all to the user(not just theres but all the information of previous users too) because its a hotel reservation thats why i want to use the i variable so it doesnt keep overwriting when a new user enter's their data.

please help!!

first function (enter the info)

#include"makefunction.h"

/*#include<stdio.h>
#include<stdlib.h>

void makereserve (void);

int main()
{

   makereserve();
		
return 0;// The main program ends here
}*/

void makefunction (void)
  { 
				 int i;
				 char first_name[12];
				 char last_name[12];
				 int adult_no=0;
				 int chil_no=0;
				 char room_type;
				 int a=0;
				 int b=0;
				 char adult_name[12];
				 char chil_name[12];
				 char date[12];
				 int night=0;
				 char type;
				 char type_b[12];
				 int room_no=0;
				 float price=0;
				 int con_no=0;
				 int age=0;
				 char age_b;
				 int amt_chil=0;
				 float price_sub=0;
				 float price_tot=0;
				 char correct;
				 int rates[12]={2000,800,1200,3000,2000,2400,3000,2500,4000,6000,4000,4800};
				 


										   printf("--__--__--__--__--__-RESERVATIONS-__--__--__--__--__--\n\n\n");
									   printf("Please enter the first name of the person making the reservation :");
									   scanf("%s",first_name);
									   printf("\n\nPlease enter the last name of the person making the reservation : ");
									   scanf("%s",last_name);
									   printf("\n\nPlease enter the age of the person making the reservation : ");
									   scanf("%d",&age);
									   if(age > 18)
									   {
											   printf("\n\nPlease enter the amount of adults : ");
											   scanf("%d",&adult_no);
											   printf("\n\nPlease enter the amount of children : ");
											   scanf("%d",&chil_no);
											   printf("\n\nAre any of the children older than the age of 13 ('Y' for yes and 'N' for no) : ");
											   scanf("%c",&correct);
											   scanf("%c",&age_b);
												  if(age_b=='Y')
												  {
													  printf("\n\nPlease enter the amount of children older than 13 : ");
													  scanf("%d",&amt_chil);
													  printf("\n\nChildren over the age of 13 are considered adults and pay adult price");
														adult_no=adult_no+amt_chil;
														chil_no=chil_no-amt_chil;
													  printf("\n\nThe amount of adults now is %d", adult_no );
												  }
												  if(adult_no==1 && chil_no<=2)
													  room_type='A';
												  else if(adult_no <=2 && chil_no<=3)
													  room_type='B';
												  else if(adult_no==3 && chil_no<=3 )
													  room_type='C';
												  else if(adult_no==4 && chil_no<=4)
													  room_type='D';
				   
											   for(a=1;a<=adult_no;a++)
											   {
													printf("\n\nPlease enter the first name of the adult number %d: ",a );
													scanf("%s",adult_name);
											   }

											   for(b=1;b<=chil_no;b++)
											   {
													printf("\n\nPlease enter the first name of child number %d:" ,b);
													scanf("%s",chil_name);
											   }
											printf("\n\nPlease enter the date this customer plan to travel : ");
											scanf("%s",date);
											printf("\n\nHow many nights does this customer plan to stay : ");
											scanf("%d",&night);
											printf("\n\nDoes this customer want to go All inclusive(A), Room only(R) or Bed and breakfast(B) :");
											scanf("%c",&correct);
											scanf("%c",&type);
											
											 if((room_type=='A') && (type=='A'))
											 {
														 price=rates[0]*night;
											 }
											 else if((room_type=='A') &&(type=='R'))
											 {
														 price=rates[1]*night;
											 }
											 else if((room_type=='A') &&(type=='B'))
											 {
														 price=rates[2]*night;
											 }
											 else if((room_type=='B') &&(type=='A'))
											 {
														 price=rates[3]*night;
											 }
											 else if((room_type=='B') &&(type=='R'))
											 {
														 price=rates[4]*night;
											 }
											 else if((room_type=='B') &&(type=='B'))
											 {
														 price=rates[5]*night;
											 }
											 else if((room_type=='C') &&(type=='R'))
											 {
														 price=rates[6]*night;
											 }			
											 else if((room_type=='C') &&(type=='B'))
											 {
														 price=rates[7]*night;
											 }
											 else if((room_type=='C') &&(type=='A'))
											 {
														 price=rates[8]*night;
											 }
											 else if((room_type=='D') &&(type=='A'))
											 {
														 price=rates[9]*night;
											 }
											 else if((room_type=='D') &&(type=='R'))
											 {
														 price=rates[10]*night;
											 }
											 else if((room_type=='D') &&(type=='B'))
											 {
														 price=rates[11]*night;
											 }
										  
											if (night<3)
											{
											   price_tot=price;
											   printf("\n\nDid not recieve a discount");
											   }
											else if ((night>3) && (night<7)) 
											{
											   price_sub=price*0.05;
											   price_tot=price-price_sub;
											   printf("\n\nRecieved a discount of 5%");
											}
											else if((night>7) && (night<14))
											{
											   price_sub=price*0.1;
											   price_tot=price-price_sub;
											   printf("\n\nRecieved a discount of 10%");
											}
											else if(night>14)																								 
											{
											   price_sub=price*0.15;
											   price_tot=price-price_sub;
											   printf("\n\nRecieved a discount of 15%");
											}
											printf("\n\nThe price for this customer is $%.2f",price );
											
									   room_no=(i*3*7)/2;
									   con_no=(i*23*12/4)*107;	 
									   
									   printf("\n\n\n**************** Reservation complete *****************\a\a\a\n\n\n");
											
									   printf("\n\nThe Room number of this customer is %d",room_no);
									   printf("\n\nThe confirmation number of this customer is %d",con_no);
									   printf("\n\nName of the reserver : %s %s",first_name,last_name);
									   printf("\n\nAmount of adults : %d",adult_no);
									   printf("\n\nAmount of children :%d",chil_no);
									   if (room_type='A') 
											printf("\n\nType of room : 1 single room");
									   else if(room_type='B')
											printf("\n\nType of room : 1 double room");
									   else if(room_type='C')
											printf("\n\nType of room : 1 triple room");
									   else if(room_type='D')
											printf("\n\nType of room : 2 double rooms");
									   if (type='A')
											printf("\n\nThe type of reservation : All inclusive");
									   else if (type='R')
											printf("\n\nThe type of reservation : Room only");
									   else if (type='B')
											printf("\n\nThe type of reservation : Bed and breakfast");
											
										 for(a=1;a<=adult_no;a++)
										 {
											 printf("\n\nName of the adult number %d :%s",a,adult_name);			  
										 }
										 for(b=1;b<=adult_no;b++)
										 {
											 printf("\n\nName of the child number %d :%s",b,chil_name);
										  }
									  printf("\n\nThe price of the accomodation of this customer is $%.2f",price_tot);
									  printf("\n\nThe hotels Account number is 098922 , the fee must be paid at any N.C.B. brach before the reserved date\n\n\n");
									}
									else if(age<18)
									{
										 printf("\n\nYou must be Older than 18 to make a reservation");
									 }

									
									   }




second function display all data

#include"viewfunction.h"
/*#include<stdio.h>
#include<stdlib.h>

void viewreserve (void);

int main()
{

   viewreserve();
		
return 0;// The main program ends here
}*/

void viewfunction(void)
{


char first_name[12];
char last_name[12];
int adult_no=0;
int chil_no=0;
char room_type[16];
int a=0;
int b=0;
int c=0;
char adult_name[12];
char chil_name[12];
char date[12];
int night=0;
char type;
char type_b[12];
int room_no=0;
int price=0;
int con_no=0;
int age=0;
char age_b;
int amt_chil=0;
float price_sub;
float price_tot;




					  

									  
				   printf("********** View Reservations **********\n\n\n");
				   for(c=1; c<=i; c++)
				   {
									   printf("-------------------------------------------------------");
									   printf("\n\nThe Room number of this customer is %d",room_no);
									   printf("\n\nThe confirmation number of this customer is %d",con_no);
									   printf("\n\nName of the reserver : %s %s",first_name,last_name);
									   printf("\n\nAmount of adults : %d",adult_no);
									   printf("\n\nAmount of children :%d",chil_no);
									   //printf("\n\nType of room : %s",room_type);
									   //printf("\n\nThe type of reservation is %s", type_b);
										 for(a=1;a<=adult_no;a++)
										 {
											 printf("\n\nName of the adult number %d :%s",a,adult_name);			  
										 }
										 for(b=1;b<=adult_no;b++)
										 {
											 printf("\n\nName of the child number %d :%s",b,chil_name);
										  }
										  system("pause");
									  //printf("\n\nThe price of the accomodation of this customer is $%f",price_tot);)
					}
}
  

This post has been edited by Jayman: 15 January 2009 - 09:18 PM


Is This A Good Question/Topic? 0
  • +

Replies To: creating arrays

#2 matthew180   User is offline

  • D.I.C Head
  • member icon

Reputation: 51
  • View blog
  • Posts: 202
  • Joined: 07-January 09

Re: creating arrays

Posted 15 January 2009 - 07:29 PM

typedef struct
{
	char first_name[12];
	char last_name[12];
	int adult_no=0;
	int chil_no=0;
	char room_type[16];
	int a=0;
	int b=0;
	int c=0;
	char adult_name[12];
	char chil_name[12];
	char date[12];
	int night=0;
	char type;
	char type_b[12];
	int room_no=0;
	int price=0;
	int con_no=0;
	int age=0;
	char age_b;
	int amt_chil=0;
	float price_sub;
	float price_tot;
} reservation;


reservation g_a_reservations[MAX_RESERVATIONS];


int
main
{
	reservation *res;
	int i;

	for ( i = 0; i < MAX_RESERVATIONS; i++ )
	{
		// do something with each reservation...  The pointer
		// is just for convenience.
		res = &g_a_reservation[i];
	}

	return 0;
}


Was This Post Helpful? 0
  • +
  • -

#3 Jayman   User is offline

  • Student of Life
  • member icon

Reputation: 423
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Re: creating arrays

Posted 15 January 2009 - 09:18 PM

Modified title to be more descriptive of the problem.
Was This Post Helpful? 0
  • +
  • -

#4 David W   User is offline

  • DIC supporter
  • member icon

Reputation: 298
  • View blog
  • Posts: 1,839
  • Joined: 20-September 08

Re: creating arrays

Posted 16 January 2009 - 03:33 PM

/*
I need first_name and last_name and all the other neccessary information in my program to be in arrays and the number that is in the brackets is i ( for eg array[i]) because that variable increases by one every time it goes back to the menu.

I really want all the information to be saved so I can display it all to the user, (not just there, but all the information of previous users too), because it's a hotel reservation and that's why I want to use the i variable ... so it doesn't keep overwriting when a new user enters their data.
*/

If you are using 'i' as an ID for that record, and want that record ID number to be unique ... then take a look at the program below, that was done a while ago for a student. It writes all the records to file and uses a linked list in memory. It may give you some ideas how to file and read back your records, and to store them in memory in a sorted linked list.
It also has a very simple password function that you can scrap or enhance. You can change the struct to be like what you want and make all the appropriate changes in the rest of the program and you could be off to a fair start on what you want ...

Shalom,
David
http://developers-he...index.php/topic,46.0.html
http://developers-he.../index.p...opic,106.0.html


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Globals ... */

#define header1 "STUDENT GRADES MANAGEMENT SYSTEM"
#define header2 "1. (I)nitialize student record list in RAM\n" \
                "2. (A)dd i.e. insert in order, by name, a NEW student record\n" \
                "3. view/(D)elete a student record\n" \
                "4. view/(E)dit a student record\n" \
                "5. (S)how all student records (as inserted BY NAME above)\n" \
                "6. (F)ile all student records presently in RAM\n" \
                "7. (R )ead all student records on file into RAM\n" \
                "8. set/change (P)assword\n" \
                "9. e(X)it"
                
#define fName "studentinfo.txt"
#define fPW "studentPW.txt" 
#define minPWLen 8
#define maxStringLen 20

#define sortRead 1

struct student
{
    int id;
    char *last;
    char *first;
    float test1;
    float test2;
    float assignment;
    float labtest;
    float finalexam;
    struct student *next;
};

typedef struct student STUDENT;
typedef STUDENT *pSTUDENT;
pSTUDENT phead = NULL;
int numStudents = 0; /* to hold 'the number of student records in memory' ...*/
int pwOK = 0;        /* to hold 'the password was OK' flag; 0=false & 1=true */
int fileFlag = 0;    /* fileFlag indicates 'the need to update the file' ... */

/* forward declarations */

pSTUDENT pID(int n);
char* getLine( FILE *fp );
char* newCopy( char* str );
void add();
void insert( pSTUDENT pS ); 
void flushStdin();
void showAll();
void viewEdit();
void viewDel();
void view(pSTUDENT pS);
void edit(pSTUDENT pS);
void del(pSTUDENT pS);
void delAll();
void init();
void scramble( char s[] );
void unscramble( char s[] );
void writeAllToFile();
void exitNowYes();
int writeFile();
int readFile();
int passWord();
int newPW();
int studentCmp( pSTUDENT pS1, pSTUDENT pS2 );

int menu()
{
    puts( header1 ); 
    if( numStudents == 1 ) puts( "Presently there is 1 record in RAM.\n" );
    else printf( "Presently there are %d records.\n\n", numStudents );
    puts( header2 );
    printf( "\nPlease enter your selection  : " );
    int selection = getchar();
    int c = selection;
    while( c!='\n' ) c=getchar(); /* 'flush' stdin */
    return selection;
}


int main() /* main start * * * * * * * * * * * * * * * * * * * * * * * * * * */
{   
    int choice, readNum;
    pwOK = passWord();
    numStudents = readFile();
    
    for(;;)/> /* Loop forever ... until 'return' ... */
    {
        if( !pwOK ) 
            pwOK = passWord();
        
        choice = -1; /*  error flag */
        choice = menu();
        /* printf("You picked %d ... \n", choice ); */
        switch( choice )
        {
            case '1': case 'i': case 'I': init(); break; /* out of 'switch' */
            case '2': case 'a': case 'A': add();  break;
            case '3': case 'd': case 'D': viewDel(); break;
            case '4': case 'e': case 'E': viewEdit(); break;
            case '5': case 's': case 'S': showAll(); break;
            case '6': case 'f': case 'F': writeAllToFile(); break;
            case '7': case 'r': case 'R':
            {
                /* If any were read ... will update Global variable phead */
                readNum = readFile(); 
                if( readNum > 0 )
                    numStudents = readNum; /* update Global numStudents */
            } 
            break;
            case '8': case 'p': case 'P': pwOK = newPW(); break; 
            case '9': case 'x': case 'X': exitNowYes(); break;
            default: puts("\nNot implemented yet ...");
        } /* end switch */
    } /* end for ... */
    return 0;
} /* main end * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/* Function definitions ... */

/* Return a pointer to the student if ID found in list; else return NULL */
pSTUDENT pID( int n )
{
    pSTUDENT p = phead;
    if( p==NULL ) return NULL; /* List empty ... so all id numbers are available */
    
    while( p!=NULL )
    {
        if( p->id == n ) return p; /* id number entered was already used */

        /* Else ... get next p to compare */
        p = p->next; 
    }  
        
    /* If reach here ... then id number not in list so ... */
    return NULL;
}

char* getLine( FILE *fp )
{
    //char buffer[maxStringLen+1];
    char * buffer = (char*) calloc( maxStringLen+1, 1 );
    int i=0, c;
    buffer[0] = 0; /* NULL terminate 'as we go' ... */
    while( (c=fgetc(fp)) != '\n' ) /* eats up WHOLE line ... including '\n' */
    {
        if( i<maxStringLen )
        {
            buffer[i] = c;
            buffer[i+1] = 0;
            ++i;
        }
        //++i;
    }
    // return strdup( buffer );
    return realloc( buffer, i+1  );
}

char* newCopy( char* str )
{
    int i, len=strlen( str );
    //while( str[len]!=0 ) ++len;
    char * nCopy = (char*) malloc( len+1 );
    for( i=0; i<len; ++i ) nCopy[i] = str[i];
    nCopy[len] = 0;
    return nCopy;
}

void flushStdin()
{
    int c;
    while( (c=getchar())!='\n' ) c=getchar(); 
}

void exitNowYes()
{
    printf("\nPress 'X' to eXit  ... ");
    int quit = getchar();
    int c = quit;
    while(c != '\n') c=getchar();   
    if( quit=='x' || quit=='X' ) 
    {
        if( fileFlag ) writeAllToFile();
        printf("\nPress 'Enter' to exit right now ... ");
        if( (quit=getchar()) == '\n' ) exit(0);
    }
    c = quit;
    while(c != '\n') c=getchar(); 
}


void add() /* ... and insert in the proper place in the list. */
{
    int ID = 0;
    printf("Enter ID         : ");
    scanf("%d", &ID); flushStdin();
    if( pID(ID) ) /* i.e. if pointer returned is NOT NULL, the id IS used */
    {
        printf("\nid %d is NOT available.\n", ID );
        return; /* Exit to menu right now ... */
    }
    /* If program reaches here, the ID just entered is available to use. */
    pSTUDENT pS = (pSTUDENT) malloc(sizeof(STUDENT));  
    pS->id = ID;
    
    //char buffer[64];
    printf("Enter Last Name  : ");
    //scanf( "%s", buffer );          flushStdin();
    //pS->last = strdup(buffer);
    pS->last = getLine(stdin);
    printf("Enter First Name : ");
    //scanf( "%s", buffer );          flushStdin();
    //pS->first = strdup(buffer); 
    pS->first = getLine(stdin);
    printf("Enter Test1      : ");
    scanf( "%f", &pS->test1 );      flushStdin();       
    printf("Enter Test2      : ");
    scanf( "%f", &pS->test2 );      flushStdin();  
    printf("Enter Assignment : ");
    scanf( "%f", &pS->assignment ); flushStdin();       
    printf("Enter Lab Test   : ");
    scanf( "%f", &pS->labtest );    flushStdin();
    printf("Enter Final Exam : ");
    scanf( "%f", &pS->finalexam );  flushStdin();

    /* Set up link to this node */
    insert( pS );
}

/* insert in list with last & first names in proper order */
void insert( pSTUDENT pS )
{
    /* Firstly, we handle the case where 'this' should be the first element. */
    if(phead == NULL || studentCmp(pS, phead) < 0) 
    {
        /* So ... it now becomes the first element ... */
        pS->next = phead; /* old phead becomes 2nd in list ... */
        phead = pS; /* and ... this pS ... becomes the head of the list */
    } 
    else /* If here ... search the linked list for the right location ... */
    { 
        pSTUDENT q = phead; /* Get a working copy of phead in q */
        /* Start comparing with element AFTER 'q' ... i.e. the 'next in' ... */
        while(q->next != NULL && studentCmp(q->next, pS) < 0) 
        {
            q = q->next; /* Traverse the list ... */
        }
        /* 
            Ok, insert after 'q' by relinking the pointers (similar to above)
            ( Includes inserting at end position ... where q->next == NULL )
        */
        pS->next = q->next; /* Inserted 'pS' is linked to 'upstream element' */
        q->next = pS;  /* Now 'q' is updated to link to the new 'pS' element */
    } 
    /* Update global variables. */
    ++numStudents; 
    fileFlag = 1;
}

void showAll()
{
    if (phead==NULL) 
    { 
        puts("\nNo records in memory at present.") ; 
        return; 
    }
    
    /* If reach here ... */
    
    pSTUDENT p = phead;
    int c;
    while( p!=NULL )
    {
        view( p );
        printf("\nPress 'Enter' to continue ... or enter 'A' to abort ... ");
        if( (c=getchar()) == 'a' || c == 'A' ) 
        {
            flushStdin();
            return;
        }
        if(c != '\n') c=getchar();
        p = p->next;
    }
}

void viewEdit()
{
    int yes = 0, ID = 0;
    printf("Enter the id number to View/Edit : ");
    scanf("%d",&ID); flushStdin();
    
    pSTUDENT p = pID(ID); /* See if pointer exists; i.e. get value or NULL */
    if( p ) /* i.e. if pointer returned above was not NULL ... */
    { 
        view(p);
        printf("\nEdit (y/n) ? ");
        yes = getchar();
        if( yes=='y' || yes=='Y' ) 
        {
            while( yes!='\n' ) yes=getchar(); /* flush stdin */
            edit(p);
        }
        else while( yes!='\n' ) yes=getchar(); /* flush stdin */
    }
    else printf("\nStudent with ID number %d not found.\n", ID);
}

void view(pSTUDENT pS)
{
    printf
    (
        "ID number  : %d\n"
        "Last Name  : %s\n"
        "First Name : %s\n"
        "Test 1     : %.2f\n"
        "Test 2     : %.2f\n"       
        "Assignment : %.2f\n"
        "Lab Test   : %.2f\n"
        "Final Exam : %.2f\n",
        pS->id, pS->last, pS->first,
        pS->test1, pS->test2, pS->assignment,
        pS->labtest, pS->finalexam
    );   
}

void edit(pSTUDENT pS)
{
    int idTmp = pS->id; /* Firstly get a backup copy of this id ... */
    
    pS->id = -1; /* Now ... reset old id number to a dummy value ... */
    int ID = 0;
    printf("Edit ID          : ");
    scanf("%d", &ID); flushStdin();
    
    if( pID(ID) ) /* i.e. if pointer returned is not NULL, this 'ID' IS USED */
    {
        printf("\nid %d is NOT available.\n", ID );
        pS->id = idTmp; /* Restore the id since this pS was NOT  edited */
        return; /* Exit to menu right now ... */
    }
    
    /* If reach hear ... */
    
    del(pS);/* Delete old record ... etc */
    
    pS = (pSTUDENT) malloc(sizeof(STUDENT)); /* get new memory for new record */
    
    pS->id = ID;
    
    //char buffer[64];
    printf("Edit Last Name   : ");
    //scanf( "%s", buffer );          flushStdin();
    //pS->last = strdup(buffer);
    pS->last = getLine(stdin);
    printf("Edit First Name  : ");
    //scanf( "%s", buffer );          flushStdin();
    //pS->first = strdup(buffer);
    pS->first = getLine(stdin);      
    printf("Edit Test1       : ");
    scanf( "%f", &pS->test1 );      flushStdin();       
    printf("Edit Test2       : ");
    scanf( "%f", &pS->test2 );      flushStdin();  
    printf("Edit Assignment  : ");
    scanf( "%f", &pS->assignment ); flushStdin();       
    printf("Edit Lab Test    : ");
    scanf( "%f", &pS->labtest );    flushStdin();
    printf("Edit Final Exam  : ");
    scanf( "%f", &pS->finalexam );  flushStdin();
    
    insert( pS );
}

void viewDel()
{
    int yes = 0, ID = 0;
    printf("Enter the id number to View/Delete : ");
    scanf("%d",&ID); flushStdin();
    
    pSTUDENT p = pID(ID); /* See if pointer exists; i.e. get value or NULL */
    if( p ) /* i.e. if pointer returned above was not NULL ... */
    { 
        view(p);
        printf("\nDelete (y/n) ? ");
        yes = getchar();
        if( yes=='y' || yes=='Y' ) { del(p); fileFlag = 1; }
        while( yes!='\n' ) yes=getchar(); /* flush stdin */
    }
    else printf("\nStudent with ID number %d not found.\n", ID);
}

void del(pSTUDENT pS)
{
    /* Handle special case of 'first in list' */
    if(  pS==phead)
    {
        phead = pS->next;
        free( pS->first );
        free( pS->last );
        free( pS );
        --numStudents; /* update globals ... */
        fileFlag = 1;
        return;   
    }
    
    /* Else not first in list, so ... */
    
    pSTUDENT p = phead; /* set p to this initial value to start loop */
    pSTUDENT pp; /* to hold the pointer to the previous record */
    
    /* Now find the pointer to the previous record. */
    while( p != pS )
    {
        pp = p; /* pp holds previous pointer value ... */
        p = p->next; /* set to next pointer in link list chain */
    }
    
    /* 
        Now we have a pointer to the previous student record, so ...
        we can now point that previous record to one past this pS record            
    */
    pp->next = pS->next;
    
    /* Now free the memory for this record and update the globals ... */
    free( pS->first );
    free( pS->last );
    free( pS);
    --numStudents;
    fileFlag = 1;
}

void delAll()
{
    pSTUDENT p = phead; /* Set p to this initial value to start loop */
    pSTUDENT pNext;     /* To hold the pointer to the next record */
    
    while( p != NULL )
    {
        pNext = p->next; /* Get a pointer to the next record. */
        free( p->first );
        free( p->last );
        free( p );
        p = pNext; /* Update p ... */
    }
    
    /* Update globals ...  */
    phead = NULL;
    numStudents = 0;
    fileFlag = 0; 
}

/* Note: calling delAll() here ... will re-set globals as above ... */
void init() 
{
    int yes;
    if( phead != NULL )
    {
        printf("\nDo you wish to overwrite the records in memory y/n ? ");
        yes = getchar();
        if( yes=='y' || yes=='Y' ) delAll(); /* re-sets globals ... */
        else
        {
            if(numStudents==1) puts("1 student record was left intact in memory.");
            else printf("%d student records were left intact in memory.\n", numStudents);
        }   
        while( yes!='\n' ) yes=getchar(); /* flush stdin */ 
    }
    else puts("\nThere were no records in memory to clear.");
}

void scramble( char s[] )
{
    int i = 0;
    int code[] = {3,1,4,1,5,9,8,6,7,0,7,0,2,8,6,9,5,3,4,2};
    while( s[i]!=0 ) { s[i] = (char) ((int)s[i] - code[i]); ++i; }
}

void unscramble( char s[] )
{    
    int i = 0;
    int code[] = {3,1,4,1,5,9,8,6,7,0,7,0,2,8,6,9,5,3,4,2};
    while( s[i]!=0 ) { s[i] = (char) ((int)s[i] + code[i]); ++i; }
}

void writeAllToFile()
{
    if( !fileFlag ) return;
    
    if( numStudents == writeFile() )
    {
        if( numStudents > 0 )
        {
            if( numStudents == 1 )
                puts("\nThe 1 student record was safely filed.");
            else
                printf
                (
                    "\nAll %d student records safely filed.\n",
                    numStudents 
                );
        }    
    }
    else
    {
        printf
        (
            "\nAn error occured while filing the student records."
            "\nPlease see the programmer for help with the problem.\n"
            "\nExiting the program now.  Press 'Enter' to continue ... "
        );
        flushStdin(); /* Holds window open to show above message. */
        exit(0); /* Return error number to system. */
    }    
}

int writeFile()
{    
    pSTUDENT p = phead;
    if( p==NULL ) 
    { 
        puts("\nNo records available ... so NO records written to file.") ; 
        return 0; 
    }
    
    FILE *fp;
    fp = fopen( fName, "w" );
    if( fp==NULL )
    {
        printf("\nError opening file %s.  Press 'Enter' to continue ... ", fName);
        flushStdin();
        return 0;
    }
    
    int count = 0; /* to track the records actually written to the file */
    while( p!=NULL )
    {
        fprintf
        (
            fp,
            "%d\n"
            "%s\n"
            "%s\n"
            "%.2f\n"
            "%.2f\n"       
            "%.2f\n"
            "%.2f\n"
            "%.2f\n",
            p->id, p->last, p->first,
            p->test1, p->test2, p->assignment,
            p->labtest, p->finalexam
        );
        
        ++count;
        p = p->next;
    }
    
    fclose( fp );
    fileFlag = 0;
    return count; /* Number of records written. */
}

int readFile()
{
    FILE *fp;
    fp = fopen( fName, "r" );
    if( fp==NULL )
    {
        printf
        (
            "\nError opening file %s.\n"
            "Perhaps it hasn't been created yet?\n"
            "Press 'Enter' to continue ... ", 
            fName
        );
        flushStdin();
        return 0; 
    }
    
    /* BUT!!! may need to delete any records in memory first. */
    init();
    
    /* 
        NOTE: we need phead to be equal to NULL in the following ...
        to be permitted to set phead ...  
        to point to the first student record in memory (read in from the file).
    */
    if( phead != NULL ) /* then exit with message ... */
    {
        if(numStudents==1)
            puts("\nThe 1 former student record was left in memory.");
        else
            printf("\nThe %d former student records were left in memory.\n", numStudents);
        return 0; /* So ...old count of student records will NOT be updated. */
    }
    
    /* Ff the program reaches here ... then ... */
    
    int count = 0, ID;
    pSTUDENT pS;
#if !sortRead
    pSTUDENT pp=NULL;
#endif
    while(  fscanf( fp, "%d", &ID) != EOF  )
    {
        pS = (pSTUDENT) malloc(sizeof(STUDENT));  
        pS->id = ID;
        
        char buffer[maxStringLen+1];
        fscanf( fp, "%s", buffer );
        pS->last = newCopy( buffer );
        //fgetc(fp); /* eats up the '\n' char left over from above 'ID read' */
        //pS->last = getLine(fp);

        fscanf( fp, "%s", buffer );
        pS->first = newCopy( buffer );
        //pS->first = getLine(fp);

        fscanf( fp, "%f", &pS->test1 );      
        fscanf( fp, "%f", &pS->test2 ); 
        fscanf( fp, "%f", &pS->assignment );        
        fscanf( fp, "%f", &pS->labtest );
        fscanf( fp, "%f", &pS->finalexam );
#if !sortRead            
        if ( pp != NULL )   /* for 2nd and up records ...*/
            pp->next = pS;  /* now previous record points to this new one */ 
        else phead =pS;     /* first record only has base pointer */
            
        pS->next = 0; /* NULL terminate list ... */
        pp = pS; /* Keep a copy of address of this pS in pp for next while loop. */
#else
        insert( pS ); 
#endif      
        ++count;
        /* printf( "\nRecord number is %d\n", count ); */
    }
    fclose( fp );
    if(count==1)
        puts("\n1 record was read into memory from the disk file.");
    else
        printf("\n%d records were read into memory from the disk file.\n", count);
        
    fileFlag = 0;
    return count; /* Total number of student records found in the file. */
}

int passWord()
{
    /* 
        Get the password in the file, if it exists, into buffer2 
        and compare it with the user entry in buffer1. 
    */
    int pwOK = 0;
    FILE *fp;
    fp = fopen(fPW, "r"); 
    if(fp==NULL) /* i.e. if file fPW doesn't exit ... */
    {
        pwOK = newPW(); /* get new password ...*/
        if( pwOK == 1 ) return 1; /* report this match of passwords back ...*/
    }
    else /* File fPW does exist ... so ... */
    {     
        //char buffer1[32];
        char *buffer1;
        char buffer2[maxStringLen+1];
        int attempts;
        
        /* Get file password into a string in buffer2. */
        fscanf( fp, "%s", buffer2 );
        fclose( fp );
        unscramble( buffer2 );
        
        /* Now ... get password entered by user into a string in buffer1. */
        for( attempts=0; attempts<3; ++attempts )
        {
            printf("Enter password: ");
            //scanf( "%s", buffer1 ); flushStdin();
            buffer1 = getLine(stdin);
            if(strcmp(buffer1, buffer2)==0) /* If true ... passwords matched. */
            {
                puts( "Match!\n" );
                free( buffer1 );
                return 1; /* Report this match of passwords back ...*/
            }
            free( buffer1 );
        }
    }
    /* if reach here ...*/
    
    printf( "NO MATCH! ... Press 'Enter' to exit ... " );
    flushStdin();
    exit(1); /* Quit the program right now ... */
}

int newPW()
{
    //char buffer1[32], buffer2[32];
    char *buffer1;
    char *buffer2;
    
    for(;;)/>
    {
         /* Get the new password into a string in buffer1. */
        printf("Enter the new password: ");
        //scanf( "%s", buffer1 ); flushStdin();
        buffer1 = getLine(stdin);
        
        if( strlen(buffer1) >= minPWLen ) break;
        
        printf("Your password must be at least %d characters ...\n", minPWLen );
        free( buffer1 );
    }
    /* 
        Get a 'verify copy' of the new password into buffer2 
        and compare it with the password in buffer1. 
    */
    printf("Enter the new password again: ");
    //scanf( "%s", buffer2 ); flushStdin();
    buffer2 = getLine(stdin);
    if(strcmp(buffer1, buffer2)==0) /* If true ... passwords matched. */
    {
        FILE *fp;
        fp = fopen(fPW, "w"); 
        if(fp==NULL)
        {
            printf("Error opening file %s ... Press 'Enter' to exit ... ", fPW);
            flushStdin();
            free(buffer2);
            free(buffer1);
            exit(2);
        }
        else
        {
            puts( "Match!\n" ); 
            scramble(buffer1);
            fprintf( fp, "%s", buffer1 );       
            fclose( fp );
            free(buffer2);
            free(buffer1);
            return 1; /* Report this match of passwords back ...*/
        }
    }
    /* If reach here ...*/
        
    printf( "NO MATCH! ... Press 'Enter' to exit ... " );
    flushStdin();
    free(buffer2);
    free(buffer1);
    exit(3); /* Quit the program right now ... */
}

/* A function to compare two student records to permit sorting ... */
int studentCmp( pSTUDENT pS1, pSTUDENT pS2 )
{
    int compare = strcmp(pS1->last, pS2->last);
    if ( compare == 0 )
        return strcmp(pS1->first, pS2->first);
    
    return compare;
}

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1