Hi I have a program that adds, deletes, edits and views a text file's contents.

The text file, named as "student.cvs" has the following content and format <student code>, <last name>, <first name>, <middle name>:

2009-1234, Asa, Gohan, Gogo
2009-4321, Basha, Bushum, Jujog
2009-1999, Mekemi, Mekeke, Makeke

The whole program code (Functions still incomplete, but is running fine):

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

#define MAX_STUD_NUM 9
#define MAX_STUD_LASTNAM 20
#define MAX_STUD_FIRSTNAM 20
#define MAX_STUD_MIDNAM 20
#define MAX_INSTRUCT_ID 5
#define MAX_INSTRUCT_NAME 50
#define OK 0
#define CANCEL -2
#define TRUE  1
#define FALSE 0
#define ERROR  -1
#define error01 1
#define error02 2
#define error03 3
#define error04 4
#define error05 5
#define error06 6

	typedef struct StudInfoType 
	{
   	char stud_num[MAX_STUD_NUM + 1];   
   	char stud_lastnam[MAX_STUD_LASTNAM + 1]; 
   	char stud_firstnam[MAX_STUD_FIRSTNAM + 1];                        
   	char stud_midnam[MAX_STUD_MIDNAM + 1];                               
	} STUDENT;

	typedef struct InstructInfoType 
	{
   	char instruct_id[MAX_INSTRUCT_ID + 1];   
   	char instruct_name[MAX_INSTRUCT_NAME + 1]; 
   	char instruct_spec;                              
	} INSTRUCTOR;

struct StudInfoType * StudRec;   
int StudRec_count = 0;                            
FILE * ptr;
int CountRecords();                                 
int SearchFiles1();
int SearchRecord(const char * string);
int SaveInfo();
int BlankCatch(const char * temp_buff);
int StudNumCatch(const char * str);
int NameCatch(const char * str);
void ViewStudRec();
void AddStudRec();
void EditStudRec();
void DelStudRec();
void ExitProg();
void error(int errType);

int main()
{
char choice[10];
     do
     {
     system("cls");
     memset(choice, '\0', 10);    
     printf("\n-----Main Menu-----\n");
     printf("[1] Student Records\n");
     printf("[2] Instructor Records\n");
     printf("[0] Exit\n\n");
     printf("Menu: ");
   	 gets(choice);
                  switch(choice[0])
       		      {
          		  case '1': StudMenu(); break;
          		  case '2': break;
        		  case '0': ExitProg(); break;
          		  default:  error(error01);
                  getch();
      	 	      } 
   	 }
     while(choice[0] != '0');
     free(StudRec);
     return 1;
}

int StudMenu()
{
char choice[10];
     if(SearchFiles1() == ERROR)
   	 {
     printf("File not found. \n");
     system("pause");
     return ERROR;
   	 }
fflush(stdin);
     do
     {
     system("cls");
     memset(choice, '\0', 10);    
     printf("\n-----Student Record-----\n");
     printf("[1] Add Record(s)\n");
     printf("[2] Edit Record(s)\n");
     printf("[3] Delete Record(s)\n");
     printf("[4] View Record(s)\n");
     printf("[0] Back to Main Menu\n\n");
     printf("Menu: ");
   	 gets(choice);
      	 	switch(choice[0])
       		{
       		case '1': AddStudRec(); break;
       		case '2': EditStudRec(); break;
       		case '3': DelStudRec(); break;
      		case '4': ViewStudRec(); break;
      		case '0': break;
       		default:  error(error01);
           	getch();
      	 	} 
   	 }
     while(choice[0] != '0');
     free(StudRec);
     return 1;
}

int CountRecords()
{   
FILE *ptr;
char array[30];
int count_file = 0;
ptr = fopen("student.cvs","rt"); 
if ( ptr==NULL ) 
{
return ERROR;
}
while(!feof(ptr))
{
fscanf(ptr, "%[^\n]\n",array );   
count_file++;                
}
fclose(ptr);
return count_file;
}

int BlankCatch(const char * temp_buff)
{    
if(strlen(temp_buff) != 0)
return FALSE;
else
return TRUE;
}

void error(int nErrorType)
{
     switch(nErrorType)
     {
     case error01: printf("Invalid input.\n"); break;
     case error02: printf("Code already exists.\n"); break;
     case error03: printf("Code does not exist.\n"); break;
     case error04: printf("Student Code must be in this format: XXXX-XXXX.\n"); break;
     case error05: printf("Names must not exceed 20 characters in length.\n"); break;
     case error06: printf("Invalid unit price.\n"); break;
     }
}

int SearchFiles1()
{
int i = 0;
int nRet = 0;                   
nRet = CountRecords();
     if ( nRet == ERROR ) 
     {
     return ERROR;
     }
StudRec_count = nRet;
StudRec = (struct StudInfoType*) malloc(StudRec_count * sizeof(struct StudInfoType)); ptr = fopen("student.csv","r"); 
char s_code[9];      
char s_lname[20];
char s_fname[20];
char s_mname[20];
     while ( fscanf( ptr, "%s %s %s%s" , s_code,s_lname,s_fname,s_mname) == 4 ) 
   	 {          
     s_code[strlen(s_code)-1] = '\0';                  
     strcpy(StudRec[i].stud_num, s_code);
	 s_lname[strlen(s_lname)-1] = '\0';
     strcpy(StudRec[i].stud_lastnam, s_lname);
     s_fname[strlen(s_fname)-1] = '\0';
     strcpy(StudRec[i].stud_firstnam, s_fname);
	 s_mname[strlen(s_mname)-1] = '\0';
     strcpy(StudRec[i].stud_midnam, s_mname);
	 i++;
	 }
     fclose(ptr);
   	 return OK;
}

int SearchRecord(const char * str)
{
int ctr = 0;
    while(ctr < StudRec_count)
    {
              if(strcmp(str,StudRec[ctr].stud_num) == 0)
       		  {
         	  return ERROR;
         	  break;
      		  }
       		  else
           	  ctr++;          
   			  }
   		      return OK;
    }

int SaveInfo()
{
   	 return ERROR;
}

void AddStudRec()
{
FILE * ptr;
ptr = fopen("student.cvs","a");

if(ptr == NULL)
{
perror("Error.");
system("pause");
exit(1);
}
     
int index = 0;
int check_name = 0;
int inPrice = 0;
char a_code[MAX_STUD_NUM + 1];
char a_lname[MAX_STUD_LASTNAM + 1];
char a_fname[MAX_STUD_FIRSTNAM + 1];
char a_mname[MAX_STUD_MIDNAM + 1];

index = 0;


    	      
do
{
again:             
fflush(stdin);
system("cls");    	 
printf("\n-----Add Student Record-----\n\n");
printf("Enter student code: ");
gets(a_code);      
index = BlankCatch(a_code);    			
            if(index == FALSE)
            {
            index = 0;
            index = StudNumCatch(a_code);	
                  if(index == ERROR)
                  {   
               	  error(error04);
                  getch();
                  goto again;
            	  }
            	  else if(index == CANCEL)
            	  {
                  fclose(ptr);
                  StudMenu();
                  break;
       		      }
            	  else
          		  {
               	  index = 0;
               	  index = SearchRecord(a_code);
             	        if(index == ERROR)
                		{
                   	    error(error02);
                   	    getch();
                   	    goto again;
                	    }
                	    else
                	    {
                    	check_name = 0;
                    	enterlastname:
                        fflush(stdin);
                        printf("Enter student last name: ");
                        gets(a_lname);                         
                        check_name = BlankCatch(a_lname);
         	                       if(check_name == FALSE)
                              	   {
                              	   check_name = 0;
                                   check_name = NameCatch(a_lname);
                                              if(check_name == ERROR)
                                  		      {
                                     	      error(error05);
                                     	      getch();
                                     	      goto enterlastname;
                                  		      }
                                  		      else if(check_name == CANCEL)
                                  		      {
                                       	      fclose(ptr);
                                     	      StudMenu();
                                     	      break;
                                  		      }
                                 	          else
                                  	          {
                                              check_name = 0;
                    	                      enterfirstname:
                                              fflush(stdin);
                                              printf("Enter student first name: ");
                                              gets(a_fname);
                                              check_name = BlankCatch(a_fname);
                        	                             if(check_name == FALSE)
                              	                         {
                                 	                     check_name = 0;
                                  	                     check_name = NameCatch(a_fname);
                                  		                            if(check_name == ERROR)
                                  		                            {
                                                                    error(error05);
                                     	                            getch();
                                     	                            goto enterfirstname;
                                  		                            }
                                  		                            else if(check_name == CANCEL)
                                  		                            {
                                       	                            fclose(ptr);
                                     	                            StudMenu();
                                     	                            break;
                                  		                            }
                                                    	            else
                                                    	            {
                                                                    check_name = 0;
                    	                                            entermiddlename:
                                                                    fflush(stdin);
                                                                    printf("Enter student middle name: ");
                                                                    gets(a_mname);
                                                                    check_name = BlankCatch(a_mname);
                                                                               if(check_name == FALSE)
                              	                                               {
                                 	                                           check_name = 0;
                                  	                                           check_name = NameCatch(a_mname);
                                                                                          if(check_name == ERROR)
                                  		                                                  {
                                     	                                                  error(error05);
                                     	                                                  getch();
                                     	                                                  goto entermiddlename;
                                  		                                                  }
                                  		                                                  else if(check_name == CANCEL)
                                  		                                                  {
                                       	                                                  fclose(ptr);
                                     	                                                  StudMenu();
                                     	                                                  break;
                                  		                                                  }
                                  		               	                                  else
                                                    	                                  {
                                                        	                              printf("Student record successfully added\n");
                                                        	                              break;
                                                    	                                  }
                   	                                                           }
                                                                    }
                                                        }
                                                        else
                                                        {
                                                        error(error01);
                                                        getch();
                                                        goto enterfirstname;
                                                        }
                                  	}
                         }
                         else
                         {
                         error(error01);
                         getch();
                         goto enterlastname;
                         }
                }       
            }
         }
         else
         {    
         error(error01);
         getch();
         system("cls");
         continue;
         }
     }
     while(index != CANCEL || check_name == CANCEL);
     fprintf(ptr,"%s, %s, %s", a_code, a_lname, a_fname);
     fflush(stdin);
     fclose(ptr);
     system("pause");
}

void EditStudRec()
{
printf("not available..2\n");
system("pause");
}

void DelStudRec()
{
printf("not available..3\n");
system("pause");
}

void ViewStudRec()
{
int ctr, ctr2;
int space;
system("cls");
printf("\n-----View Student Records-----\n\n");
printf("Student Code");
printf("\ttLast Name");
printf("\tFirst Name");
printf("\tMiddle Name");
printf("\n");
    for(ctr = 0 ;ctr < StudRec_count;ctr++)
    {
    printf("\t%s",StudRec[ctr].stud_num);
    printf("\t%s",StudRec[ctr].stud_lastnam);
    strlen(StudRec[ctr].stud_lastnam);
    space =(16 - strlen(StudRec[ctr].stud_lastnam));
    printf("\t%s",StudRec[ctr].stud_firstnam);
    strlen(StudRec[ctr].stud_firstnam);
    space =(16 - strlen(StudRec[ctr].stud_firstnam));
    printf("\t%s",StudRec[ctr].stud_midnam);
    strlen(StudRec[ctr].stud_midnam);
    space =(16 - strlen(StudRec[ctr].stud_midnam));
          for(ctr2 = 0;ctr2<space+1;ctr2++)
          {
          printf(" ");
          }
    }
    system("pause");
}

int StudNumCatch(const char * str)
{
int c;
    if(strcmp(str,"000") == 0)
    {
    return CANCEL;
    }
    else if(strlen(str)<MAX_STUD_NUM || strlen(str)>MAX_STUD_NUM)
    {
    return ERROR;
    }
    else
    {   
    return OK;
    }
    while((c = *(str++)) != '\0')
    {
             if(c >= 58 && c<= 126)
             {
             return ERROR;
             }
             else
             {   
             return OK;
             }
   }
}

int NameCatch(const char * str)
{
int c;
    if(strcmp(str,"000") == 0)
    {
    return CANCEL;
    }
    else if(strlen(str) > MAX_STUD_LASTNAM)
    {
    return ERROR;
    }
    while((c = *(str++)) != '\0')
    {
             if(isdigit(c))
             {
             return ERROR;
             }
             else
             {
             return OK;
             }
   }
}

void ExitProg()
{
system("cls");
printf("\nPROGRAM TERMINATED\n\n\n");
system("pause");
}

My view function is returning something odd. Can anyone point out or fix this?

For review this is the View Student Records function:

void ViewStudRec()
{
int ctr, ctr2;
int space;
system("cls");
printf("\n-----View Student Records-----\n\n");
printf("Student Code");
printf("\ttLast Name");
printf("\tFirst Name");
printf("\tMiddle Name");
printf("\n");
    for(ctr = 0 ;ctr < StudRec_count;ctr++)
    {
    printf("\t%s",StudRec[ctr].stud_num);
    printf("\t%s",StudRec[ctr].stud_lastnam);
    strlen(StudRec[ctr].stud_lastnam);
    space =(16 - strlen(StudRec[ctr].stud_lastnam));
    printf("\t%s",StudRec[ctr].stud_firstnam);
    strlen(StudRec[ctr].stud_firstnam);
    space =(16 - strlen(StudRec[ctr].stud_firstnam));
    printf("\t%s",StudRec[ctr].stud_midnam);
    strlen(StudRec[ctr].stud_midnam);
    space =(16 - strlen(StudRec[ctr].stud_midnam));
          for(ctr2 = 0;ctr2<space+1;ctr2++)
          {
          printf(" ");
          }
    }
    system("pause");
}

Please help. Domou arigatou.

Recommended Answers

All 4 Replies

It's no point posting ~500 lines of code and then asking someone to "fix" your code. Make an attempt to post the smallest amount of code that isolates your problem. You never know, by trying to do this you may actually work out what the problem is for yourself.

A few things to fix:

1) Don't use fflush(stdin) - it's WRONG!

2) Make up your mind what name you want for your file - is it students.cvs or students.csv - you use both names in your program.

3) Use the function fgets() in place of gets()

4) You're using "magic" numbers e.g. 58, 126

5) As far as your ViewStudRec() function is concerned - get rid of the inner for loop that prints spaces (you're already at the end of the line) and just print a newline character. After you fix that, you just need to change your code so your data is aligned directly under your column headings.

Thanks for pointing out.

Ok so far I got this fix in my view student record function:

void ViewStudRec()
{
int ctr, ctr2;
int space;
system("cls");
printf("\n-----View Student Records-----\n\n");
printf("Student Code");
printf("\tLast Name");
printf("\tFirst Name");
printf("\tMiddle Name");
printf("\n");
    for(ctr = 0 ;ctr < StudRec_count;ctr++)
    {
    printf("%s",StudRec[ctr].stud_num);
    printf("\t%s",StudRec[ctr].stud_lastnam);
    printf("\t%s",StudRec[ctr].stud_firstnam);
    printf("\t%s",StudRec[ctr].stud_midnam);
    strlen(StudRec[ctr].stud_midnam);
    space =(16 - strlen(StudRec[ctr].stud_midnam));
          for(ctr2 = 0;ctr2<space+1;ctr2++)
          {
          printf(" ");
          }
    }
    system("pause");
}

And this is my output:
[IMG]http://img198.imageshack.us/img198/4903/cviewstudrec.jpg[/IMG]


Well I don't mind about the aligning of my output columns, but where the heck did those other unecessary outputs come from?

If I change your ViewStudRec() function to this:

void ViewStudRec() {
    int ctr, ctr2;
    int space;
    system("cls");
    printf("\n-----View Student Records-----\n\n");
    printf("Student Code");
    printf("\tLast Name");
    printf("\tFirst Name");
    printf("\tMiddle Name");
    printf("\n");
    for (ctr = 0; ctr < StudRec_count; ctr++) {
        printf("%s", StudRec[ctr].stud_num);
        printf("\t%s", StudRec[ctr].stud_lastnam);
        printf("\t%s", StudRec[ctr].stud_firstnam);
        printf("\t%s", StudRec[ctr].stud_midnam);
//        strlen(StudRec[ctr].stud_midnam);
//        space = (16 - strlen(StudRec[ctr].stud_midnam));
//        for (ctr2 = 0; ctr2 < space + 1; ctr2++) {
//            printf(" ");
//        }
        printf("\n");
    }
    system("pause");
}

This is the output I get:

-----View Student Records-----

Student Code	Last Name	First Name	Middle Name
2009-1234	Asa	Gohan	Gog
2009-4321	Basha	Bushum	Jujo
2009-1999	Mekemi	Mekeke	Makek
Press any key to continue . . .

I'm not sure why you keep on insisting using that inner for loop for printing out spaces - when you reach the end of the line, just print a new line character.

As for your strange output - well I'm not sure. Obviously you're accessing other areas of memory within your program. If you know how to use a debugger, then I would try stepping through this function and watch the values of your fields before they're output.

If I change your ViewStudRec() function to this:

void ViewStudRec() {
    int ctr, ctr2;
    int space;
    system("cls");
    printf("\n-----View Student Records-----\n\n");
    printf("Student Code");
    printf("\tLast Name");
    printf("\tFirst Name");
    printf("\tMiddle Name");
    printf("\n");
    for (ctr = 0; ctr < StudRec_count; ctr++) {
        printf("%s", StudRec[ctr].stud_num);
        printf("\t%s", StudRec[ctr].stud_lastnam);
        printf("\t%s", StudRec[ctr].stud_firstnam);
        printf("\t%s", StudRec[ctr].stud_midnam);
//        strlen(StudRec[ctr].stud_midnam);
//        space = (16 - strlen(StudRec[ctr].stud_midnam));
//        for (ctr2 = 0; ctr2 < space + 1; ctr2++) {
//            printf(" ");
//        }
        printf("\n");
    }
    system("pause");
}

This is the output I get:

-----View Student Records-----

Student Code	Last Name	First Name	Middle Name
2009-1234	Asa	Gohan	Gog
2009-4321	Basha	Bushum	Jujo
2009-1999	Mekemi	Mekeke	Makek
Press any key to continue . . .

I'm not sure why you keep on insisting using that inner for loop for printing out spaces - when you reach the end of the line, just print a new line character.

As for your strange output - well I'm not sure. Obviously you're accessing other areas of memory within your program. If you know how to use a debugger, then I would try stepping through this function and watch the values of your fields before they're output.

Hey thanks, of course, my bad, sorry I didn't think of it that way. Yeah I was just about examining which of the memory access I've messed up, as I tested it with the other machines.

Anyway, I solved my view function, thanks a bunch.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.