How to work with nested structures in C in binary mode - c

I have to make an exam system with making an exam, taking it,storing the points that i got from the exam in the students data.I was trying to do it with nested structures.I stored the information but after making an exam and taking it i couldn't update a specific data inside the nested structure
This is the structure:
struct quest
{
char question[MAX_LIMIT];
char ans1[10],ans2[10],ans3[10],ans4[10];
char answer[10];
int count;
}q;
struct subject{
quest q[50];
}bio,math;
This is the part to make the exam.//Not the part with the problem
void create_exam()
{
int ch,start_count=0;
char n;
FILE *f,*fp;
printf("What subject do you want to create\n1.Biology \n2.Math\n");
scanf("%d",&n);
if(n==1)
{
f=fopen(name_bio,"wb");
if(f==NULL)
{
printf("Error!\n");
return;
}
printf("Exams have a standard with 6 questions!!");
for(int i=1;i<=6;i++)
{
fflush(stdin);
printf("\nGive the question number %d: ",i);
scanf("%[^\n]%*c",bio.q[i].question);
printf("\nGive the alternatives for the question %d: \n",i);
fflush(stdin);
scanf("%[^\n]%*c\n",bio.q[i].ans1);
scanf("%[^\n]%*c\n",bio.q[i].ans2);
scanf("%[^\n]%*c\n",bio.q[i].ans3);
scanf("%[^\n]%*c",bio.q[i].ans4);
printf("Give the correct answer: ");
scanf("%[^\n]%*c",bio.q[i].answer);
bio.q[i].count=start_count;
}
size_t unitsWritten=fwrite(&bio,sizeof(struct subject),1,f);
if(unitsWritten==0){
perror("\n\n Data not saved"); }
else printf("\nData saved!");
fclose(f);
return;}
else if(n==2)
{// the same thing with the other subject
And this is the part with the problem.The part that takes the exam.The problem is that when i want to update the mistake counter for question it doesn't print the questions anymore in the screen. Just the part that says "Question number %d" and than is blank space
void get_exam()
{
int temp;
int id_temp;
int n,sum=0;
char ans[20];
FILE *finside;
finside=fopen(file_person,"rb+");
if(finside==NULL)
{
printf("Error in file");
return;
}
printf("\nGive the Id : ");
scanf("%d",&id_temp);
nr_person=get_nr();//to get the number of students saved
bool found=false; //The part to check if the student ID is found so he can make the exam
for(int i=0;i<nr_person;i++)
{ fseek(finside,i*sizeof(struct person),SEEK_SET);
fread(&nr1[i],sizeof(struct person),1,finside);
if(id_temp==nr1[i].id)
{
found=true;
temp=id_temp;}
}
if(found==false)
{
perror("\nId not found!");
return;
}
printf("Choose the subject:\n");
printf("1.Biology\n");
printf("2.Math\n");
scanf("%d",&n);
switch (n)
{
case 1:
FILE *f;
f=fopen(name_bio,"rb+");
if(f==NULL)
{
printf("Gabim ne hapjen e file");
return;
}
int nr;
system("cls");
printf("====Start=====\n");
for(int k=1;k<=6;k++)
{
//fseek(f,sizeof(struct quest)*(k-1),SEEK_SET);
fread(&bio,sizeof(struct subject),1,f);
fflush(stdin);
printf("\nQuestion nr %d\n",k);
printf("%s\n",bio.q[k].question);
printf("%s\n",bio.q[k].ans1);
printf("%s\n",bio.q[k].ans2);
printf("%s\n",bio.q[k].ans3);
printf("%s\n",bio.q[k].ans4);
printf("Give the correct answer:");
scanf("%[^\n]%*c",ans);
if(strcmp(info.q[k].answer,ans)==0)
{
sum++;
}
else if(strcmp(info.q[k].ans4,ans)==0)
{
sum=+0;
}
else
{
sum--; //This is the part i can't do right.How can i use the `fseek` and `fwrite` right
bio.q[k].count++; //in this case
fseek(f,(k-1)*sizeof(struct quest),SEEK_SET);
fwrite(&bio.q[k].count,sizeof(struct quest),1,f);
}
}
size_t unitsWritten=fwrite(&bio,sizeof(struct lenda),1,f);
if(unitsWritten==0){
perror("\n\n Data not saved"); }
else printf("\nData saved!");
printf("\nThe exam is over!\n");
printf("\nU got %d points",sum);
//The part to save the points to students
/*
for(int i=0;i<nr_person;i++)
{
******
}
fclose(f);//File for the bio exam
fclose(finside);//File for student data
break;
Thank you in advance!!

Related

How to delete a record when there's more than one record of the same name in C

I am working on code for s blood donation system. I'm currently struggling with the delete donor record function.
The delete record function is to delete the record of a donor with a given name. If there are two or more records with the same name in the file then the program asks for mobile number. While there may be more than one person with the same name, each person has a unique mobile number.
My problem is that when the same name is used for several records, the wrong record is deleted.
If there's only one record with that name, the program deletes the record in the manner that's required.
(The variable i is declared globally as int i)
Here's the delete function
void delete(struct blood *b,int n)
{
char name[50];
int phone;
int found=0;
int c=0;
FILE *fp = fopen("bloodrecord.txt", "r");
FILE *fp1 = fopen("temp.txt", "w");
printf("\nEnter Name: ");
scanf("%s", name);
printf("---------------------------------------------\n");
while(fread(&b[i],sizeof(struct blood),1,fp))
{
if(strcmpi(b[i].name,name)==0)
{
c=c+1;
printf("\nName: %s\n",b[i].name);
printf("Age: %d\n", b[i].age);
printf("Mobile no.: %d\n", b[i].phone);
printf("Blood group: %s\n", b[i].bg );
printf("Weight: %d\n", b[i].weight);
printf("Sex: %s\n",b[i].sex);
printf("Address: %s\n",b[i].add);
printf("\n");
if (c==1)
{
found=1;
}
else if(c>1)
{
printf("\nThere are more than one occurences of this name in the records\n");
printf("\nPlease enter the mobile number of the donor: ");
scanf("%d", &phone);
if (b[i].phone == phone)
{
found=1;
}
}
}
else
fwrite(&b[i],sizeof(struct blood),1,fp1);
}
fclose(fp);
fclose(fp1);
if (found==1)
{
fp1 = fopen("temp.txt", "r");
fp = fopen("bloodrecord.txt", "w");
while(fread(&b[i],sizeof(struct blood),1,fp1))
{
fwrite(&b[i],sizeof(struct blood),1,fp);
}
fclose(fp);
fclose(fp1);
}
else
{
printf("\n\aRECORD DOES NOT EXIST.\n");
}
printf("RECORD SUCCESSFULLY DELETED");
getchar();
getchar();
}
I suggest that to make the program simpler, you request both the donor's name and the donor's mobile number at the beginning.
Then you process the input file and look for both name and mobile number in a single pass.
I started with your code and made a few changes. See comments.
Please note that I have not tested this code nor compiled it. It should be essentially correct however there may be a compiler error if I made a syntax mistake.
I assume that the you are using the struct blood correctly in your code since you did not provide the code defining that struct.
I assume that an int is sufficiently large to hold the mobile number. Since the size of an int can vary and is determined by the compiler, it may or may not be large enough for a mobile number. See Range of values in C Int and Long 32 - 64 bits
One thing I do not understand is why you are using the b[i] syntax and where is the variable i defined? You could instead use a local variable in the delete() function.
I also have the delete() function returning a value indicating if it found a match or not. This may or may not be useful.
int delete()
{
struct blood b;
char name[50] = {0};
int phone;
int found = 0;
FILE *fp = fopen("bloodrecord.txt", "r");
FILE *fp1 = fopen("temp.txt", "w");
// Ask for the donor's mobile number along with their name
// at the beginning to make the search easier and be able to
// do this in a single pass.
printf("\nEnter Name of the donor: ");
scanf("%49s", name); // Oka's comments about scanf().
printf("\nPlease enter the mobile number of the donor: ");
scanf("%d", &phone);
printf("---------------------------------------------\n");
while(fread(&b, sizeof(struct blood), 1, fp))
{
// check both donor's name and donor's mobile number.
if(strcmpi(b.name, name) == 0 && b.phone == phone)
{
// print out the donor data and indicate we are deleting
// this donor record.
printf("Deleting donor record\n");
printf(" Name: %s\n", b.name);
printf(" Age: %d\n", b.age);
printf(" Mobile no.: %d\n", b.phone);
printf(" Blood group: %s\n", b.bg );
printf(" Weight: %d\n", b.weight);
printf(" Sex: %s\n", b.sex);
printf(" Address: %s\n", b.add);
printf("\n");
found = 1;
}
else {
// we are keeping this donor record so write it to the
// temp file.
fwrite(&b, sizeof(struct blood), 1, fp1);
}
}
fclose(fp);
fclose(fp1);
if (found == 1)
{
// file temp.txt has deleted donors so lets updated
// the original file, bloodrecord.txt, with the updated
// list of donors.
fp1 = fopen("temp.txt", "r");
fp = fopen("bloodrecord.txt", "w");
while(fread(&b, sizeof(struct blood), 1, fp1))
{
fwrite(&b, sizeof(struct blood), 1, fp);
}
fclose(fp);
fclose(fp1);
printf("RECORD SUCCESSFULLY DELETED");
}
else
{
printf("\n\aRECORD DOES NOT EXIST.\n");
}
getchar();
getchar();
return found; // indicate if we found a match or not.
}
I reused most of your code, and added a second pass to handle the actual delete (first pass searches for matching records).
void delete(struct blood *b,int n)
{
const int MOBILE_SIZE = 16;
char name[50];
int phone = 0;
int found=0;
int c=0;
FILE *fp = fopen("bloodrecord.txt", "r");
FILE *fp1 = fopen("temp.txt", "w");
printf("\nEnter Name: ");
scanf("%s", name);
printf("---------------------------------------------\n");
while(fread(&b[i],sizeof(struct blood),1,fp))
{
if(strcmpi(b[i].name,name)==0)
{
c=c+1;
printf("\nName: %s\n",b[i].name);
printf("Age: %d\n", b[i].age);
printf("Mobile no.: %d\n", b[i].phone);
printf("Blood group: %s\n", b[i].bg );
printf("Weight: %d\n", b[i].weight);
printf("Sex: %s\n",b[i].sex);
printf("Address: %s\n",b[i].add);
printf("\n");
found = 1;
}
}
/* Finished the first pass. Now, start again */
rewind(fp)
if (c > 1) {
printf("There are multiple records for the name %s\n", name);
printf("\nEnter Mobile Number: ");
scanf("%d", &phone);
}
while(fread(&b[i],sizeof(struct blood),1,fp))
{
if((c == 1 && strcmpi(b[i].name,name)==0)
|| (c > 1 && strcmpi(b[i].name,name) == 0 && b[i].mobile == mobile))
continue; /* skip this record */
}
else
fwrite(&b[i],sizeof(struct blood),1,fp1);
}
fclose(fp);
fclose(fp1);
if (found==1)
{
fp1 = fopen("temp.txt", "r");
fp = fopen("bloodrecord.txt", "w");
while(fread(&b[i],sizeof(struct blood),1,fp1))
{
fwrite(&b[i],sizeof(struct blood),1,fp);
}
fclose(fp);
fclose(fp1);
}
else
{
printf("\n\aRECORD DOES NOT EXIST.\n");
}
printf("RECORD SUCCESSFULLY DELETED");
getchar();
getchar();
}

My basic trade program in C does not store any modifications when I close command prompt

#include<stdio.h>
int main() {
//After selling and buying i want it to modify this
struct music {
int srno;
char name[10];
int upperlimit;
int lowerlimit;
int avarn;
};
//Structure to maintain personal data
struct custormer {
int srno;
char name[5];
int upperlimit;
int lowerlimit;
int avarn;
};
FILE *f1;
int choice,amount,price;
int x,code,j=0;
struct music m1[] = {1,"Apple",100,98,10,2,"Valve",100,98,10,3,"Google",90,80,10,4,"Tesla",100,98,10};
struct music m2[10];
f1 = fopen("4.DAT","rb+");
if(f1==NULL)
{
printf("File does not exist!");
exit(0);
}
while(1)
{
printf("___________________________________\n");
printf("MENU\n");
printf("___________________________________\n");
printf("1) Stock Market\n");
printf("2) Buy\n");
printf("3) Personal Info\n");
printf("4) Sell\n");
printf("5) Exit\n");
printf("Enter choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
printf("Stock Market\n");
printf("___________________________________\n");
for(x=0;x<4;x++)
{
printf("%d\t %s\t %d\t %d\t %d\n",m1[x].srno,m1[x].name,m1[x].upperlimit,m1[x].lowerlimit,m1[x].avarn);
fwrite(&m1,sizeof(m1),1,f1);
}
break;
}
case 2:
{
printf("Enter code of Stock:");
scanf("%d",&code);
printf("Enter number of stocks:");
scanf("%d",&amount);
printf("Enter price:");
scanf("%d",&price);
rewind(f1);
for(x=0;x<4;x++)
{
if(price>m1[x].lowerlimit&&price<m1[x].upperlimit)
{
if(m1[x].srno==code)
{
printf("Trasaction Is Succesful\n");
m1[x].avarn = m1[x].avarn-amount;
fwrite(&m1,sizeof(m1),1,f1);
m2[j].srno = j+1;
strcpy(m2[j].name,m1[x].name);
m2[j].avarn = amount;
j++;
}
}
}
break;
}
case 3:
{
for(x=0;x<j;x++)
{
printf("%d\t %s\t %d\n ",m2[x].srno,m2[x].name,m2[x].avarn);
fseek ( f1, sizeof(m1), SEEK_CUR ) ;
fwrite ( &m2, sizeof(m2), 1, f1 ) ;
}
break;
}
case 4:
{
printf("Enter code of stock to sell:");
scanf("%d", &code);
printf("Enter amount to sell:");
scanf("%d",&amount);
printf("Enter price to sell:");
scanf("%d",&price);
for(x=0;x<4;x++)
{
if(price>m1[x].lowerlimit&&price<m1[x].upperlimit)
{
if(m1[x].srno==code)
{
printf("Transaction is Sucessful\n");
m1[x].avarn = m1[x].avarn+amount;
fwrite(&m1,sizeof(m1),1,f1);
}
}
}
break;
}
case 5:
{
printf("Thanks!");
exit(0);
}
default:
{
printf("Invalid input!");
exit(0);
break;
}
}
}
fclose(f1);
return 0;
}
The program will execute and run but it will not store any data that I add when I buy or sell stocks, I'm still learning file operations, can someone correct this program or tell me how to do it? I feel like the fwrite() function is maybe not taking in the values I'm giving it The program will execute and run but it will not store any data that I add when I buy or sell stocks, I'm still learning file operations, can someone correct this program or tell me how to do it? I feel like the fwrite() function is maybe not taking in the values I'm giving it
You are using the wrong operator for testing equality.
if(f1=NULL)
This statement will assign NULL to f1, which will then evaluate to false.
You should use if (f1 == NULL) to test if it's NULL. Or just simply if (f1).
Something else strange that you are doing is opening the file twice, leaking the first handle. You should close it first, or open it only once.
Also, you should pay attention to the open mode. Your second call will actually destroy the file's contents. Read the documentation.

C - Crashing when using Realloc on a Pointer inside a Struct

I've been writing a small program that will allow the user to read a file, create a small "database" and the ability to create / delete entries, etc. When I try to use the
realloc()
function, it crashes.
Not sure if I am doing something wrong, probably am though, since I'm rather new to C.
So, I try to do it this way:
StudentDB database;
//More code in between, that does include malloc()
database->students = realloc(database->students, (database->numberOfStudents + 1) * sizeof(Student));
//It crashes when it gets to that part.
What I am trying to do is use the realloc() function for a pointer that's inside a struct.
This is the entire program so far:
#include <stdio.h>
#include <stdlib.h>
typedef struct Lesson {
char *name;
int semester;
float grade;
} Lesson;
typedef struct Student {
char *name;
char *surname;
int id;
int numberOfLessons;
Lesson *lesson;
} Student;
typedef struct Database {
int numberOfStudents;
Student *student;
} StudentDB;
static int maxNameSize = 100;
static int autoclear = 1;
void addStudent(FILE *studentFile, StudentDB *database) {
database->numberOfStudents++;
printf("\nAdded +1 to number of students");
database->student = realloc(&database->student, 10);
//
// printf("Name of the student: ");
// scanf("%s", database.student[database.numberOfStudents].name);
}
void clear() {
if(autoclear) {
system("cls");
}
}
Lesson getNextLesson(FILE *studentFile) {
Lesson lesson;
lesson.name = malloc(maxNameSize * sizeof(char));
if(!lesson.name) { printf("Memory Allocation has failed. Exiting the program!"); exit(0); }
fscanf(studentFile, "%s", lesson.name);
fscanf(studentFile, "%d", &lesson.semester);
fscanf(studentFile, "%f", &lesson.grade);
printf("\n\t%s %d || %.2f\n", lesson.name, lesson.semester, lesson.grade);
return lesson;
}
Student getNextStudent(FILE *studentFile) {
Student student;
student.name = malloc(maxNameSize * sizeof(char));
if(!student.name) { printf("Memory Allocation has failed. Exiting the program!"); exit(0); }
fscanf(studentFile, "%s", student.name);
student.surname = malloc(maxNameSize * sizeof(char));
if(!student.surname) { printf("Memory Allocation has failed. Exiting the program!"); exit(0); }
fscanf(studentFile, "%s", student.surname);
fscanf(studentFile, "%d", &student.id);
fscanf(studentFile, "%d", &student.numberOfLessons);
printf("%d || %s %s || %d\n", student.id, student.name, student.surname, student.numberOfLessons);
int lesson;
student.lesson = malloc(student.numberOfLessons * sizeof(Lesson));
for(lesson = 0; lesson < student.numberOfLessons; lesson++) {
student.lesson[lesson] = getNextLesson(studentFile);
}
return student;
}
void loadStudents() {
}
void run(FILE *studentFile, StudentDB *database) {
int answer;
do {
clear();
answer = menu();
switch(answer) {
case 1: {
break;
}
case 2: {
break;
}
case 3: {
addStudent(studentFile, &database);
break;
}
case 4: {
break;
}
}
} while(answer < 0 || answer > 9);
}
int menu() {
int answer;
printf("1. Load students records from file\n");
printf("2. Save students records to file\n");
printf("3. Add a student record\n");
printf("4. Delete a student record by student id\n");
printf("5. Display a student record by student id\n");
printf("6. Display a student record by student surname\n");
printf("7. Display all student records\n");
printf("8. Find the lesson average for all students\n");
printf("9. Exit\n");
printf("Enter the number of the thing you would like to do: ");
// scanf("%d", &answer);
return 3;
}
void programInfo() {
printf("\n\n====================================================\n\tProgram Info\n\n This program was created by KKosyfarinis\n\n KKosyfarinis#uth.gr\n====================================================\n\n");
}
void readData(FILE *studentFile, StudentDB *db) {
int i;
printf("Running the loop\n");
for(i = 0; i < db->numberOfStudents; i++) {
printf("=====================\n\n\tStudent #%d\n", i);
db->student[i] = getNextStudent(studentFile);
printf("\n\tCompleted\n\n=====================\n");
}
clear();
}
void saveStudents() {
}
void main() {
system("color 02");
system("#echo off");
FILE *studentFile;
StudentDB database;
studentFile = fopen("students.txt", "r+w");
int numberOfStudents;
//Set the number of students
fscanf(studentFile, "%d", &database.numberOfStudents);
//Prints the number of students
printf("Number of students: %d\n", database.numberOfStudents);
//Set the memory allocation
database.student = malloc(database.numberOfStudents * sizeof(Student));
if(!database.student) {
printf("The memory allocation has failed. Exiting the program!");
exit(0);
}
//Read the students
readData(studentFile, &database);
programInfo();
run(studentFile, &database);
}
Thanks in advance for any help!
You're two code blocks have differing lines. One of which (the larger one) is incorrect. You are passing in a dereference to the student pointer? That's not needed, just pass the pointer itself.
database->student = realloc(&database->student, 10);
Should be:
database->student = realloc(database->student, 10);
You are also not passing in a realistic size, but your first code sample was. Does the following line not work?
database->students = realloc(database->students, (database->numberOfStudents + 1) * sizeof(Student));
That was just copied from your question. I'm confused as to what you have/have not tried and which one gives you the error.
Also, in the future provide more of a minimal example that still produces the error. There's also a chance you would figure out the issue while stripping the code down.
What with this line ?
addStudent(studentFile, &database);
in run function ? Where pointer to local variable is taken and passed to addStudent function
void run(FILE *studentFile, StudentDB *database) {
...
case 3: {
addStudent(studentFile, &database); // <-- get pointer to local variable
i think this code cannot work even with Nick's changes without this modification
addStudent(studentFile, database);

making a program to add a list of names in 2d array actually I just made a part of it and I have a lot of errors

my code is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char names[10][31];
int u=0;
char new[31];
int ctr=1;
int notInList=0;
int y=0;
int i=0;
char *p;
strcpy(names[0],"mahmoud");
while(1)
{
printf("\t\t§§§Menu items§§§\n");
printf("1==>enter a new name\n");
printf("2==>search for a name\n");
printf("3==>delete a name from the list\n");
printf("Note !!.. ((if you want to exit the program press(1)and then type ((exit))\n");
fflush(stdin);
scanf("%i",&u);
notInList=1;
if(u==1)
{
printf("please enter a name : ");
fflush(stdin);
gets(new);
_strlwr(new);
if(strcmp(new,"exit")==0)
{
printf("bye bye\n");
break;
}
else
{
notInList=1;
for(int i=0;i<=ctr;i++)
{
p=strstr(new,names[i]);
if(strcmp(new,names[i])==0)
{
printf("the name is already exist\n");
break;
}
else if (p)
{
printf("did you mean (( %s ))\n",names[i]);
printf("1==>yes\n");
printf("2==>no\n");
fflush(stdin);
scanf("%d",&y);
if(y==1)
{
printf("the name is already exist\n");
break;
}
else if(y==2)
{
notInList=0;
strcpy(new,names[ctr]);
ctr++;
break;
}
else printf("plz enter a number from the list");
}
else
{
notInList=0;
}
}
if(notInList==0)
{
strcpy(new,names[ctr]);
ctr++;
for(int i=0;i<ctr;i++);
{
printf("%d==>%s\n",i+1,names[i]);
}
}
// break;
}
}
return 0;
}
the first problem is: when I enter ( 1) and then add a name is similar to the first name it printf to me did you mean ( )//// without a name
the second is when I want to add a new name it doesn't please help me
notice that he program is not finished only the first choise

Checking if an array of structures is 'empty' in C

I'm making a program that sort of acts like a student records system using an array of structures within structures. The program allows adding, editing and viewing student profile and their corresponding information. I'm having trouble with my displayAll function, when checking if a structure is empty. Supposedly if no subject information has been added to a student profile yet I'm supposed to display a message saying so and display their subject they're enrolled in otherwise. But I'm quite confused how to do so. Some tips would be much appreciated.
I've omitted some parts of the code to put emphasis on the displayAll function.
Someone pointed out this thread: Checking if an array of structs is empty or not, but it doesn't really halp me fully as I am dealing with an array of structures within an array of structures.
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
#include <ctype.h>
struct name{
char fname[30];
char lname[20];
char mi;
};
struct local{
char address[30];
char city[20];
};
struct subjs{
char courseCode[10];
char courseDes[20];
char grade;
};
struct student{
char id[8];
struct name studName;
struct local place;
struct subjs course[4];
};
void inputInfo(struct student *studInfo);
void addSubjects(struct student *studInfo);
void displayAll(struct student info[], int limit);
int main(){
struct student info[12];
int i=0, j, courseLimit=0;
char choice;
char idVerify[8];
do{
printf("MENU");
printf("\n\n[A] Add student Information");
printf("\n[B] Add student subject");
printf("\n[C] Edit student address or city");
printf("\n[D] Edit subject grade");
printf("\n[E] View individual student info/subjects");
printf("\n[F] View all students with their corresponding subjects");
printf("\n[g] Quit");
printf("\n\nEnter choice: ");
choice=tolower(getche());
system("cls");
switch (choice){
case 'a':
inputInfo(&info[i]);
i++;
break;
case 'b':
printf("Enter you id number for verification: ");
gets(idVerify);
for(j=0; j<i; j++){
if(strcmp(idVerify, info[j].id) == 0){
addSubjects(&info[j]);
}
else
printf("ID Number not found");
}
break;
case 'c':
//codes
break;
case 'd':
//codes
break;
case 'e':
//codes
break;
case 'f':
displayAll(info, i);
break;
case 'g':
printf("This program will now close.\nPress any key to continue.");
break;
default: printf("Invalid character. Try again");
break;
}
getch();
system("cls");
}while (choice!='g');
}
void inputInfo(struct student *studInfo){
//codes
}
void addSubjects(struct student *studInfo){
//codes
}
void displayAll(struct student info[], int limit){
int i, j;
if(limit == 0){
printf("Records are empty");
}
else{
for(i=0; i<limit; i++){
printf("\nStudent Name: %s %c %s", info[i].studName.fname, info[i].studName.mi, info[i].studName.lname);
printf("\nID Number: %s", info[i].id);
printf("\nAddress and city: %s, %s", info[i].place.address, info[i].place.city);
if(info[i].course[j].courseCode == 0){
printf("\nNo enrolled subjects");
}
else{
printf("\nSubjects:");
for(j=0; j<4; j++){
if(info[i].course[j].courseCode != 0){
printf("Subject %d", j+1);
printf("\nCourse Code: %s", info[i].course[j].courseCode);
printf("\nCourse Description: %s", info[i].course[j].courseDes);
printf("\nCourse Grade: %c", info[i].course[j].grade);
printf("\n");
}
}
}
}
}
}
You can use a flag to track wether a subject has been found in the subject for loop. I would name it found and clear it before the loop. Then set it within the loop, when a subject has been found. If the flag is still cleared after the loop, then print the desired message. To print the header "Subjects", you can check within the loop if a subject has been found (and printed) before.
Example code:
int found = 0; // clear flag
for(j=0; j<=4; j++){
if(info[i].course[j].courseCode != 0){
if(!found) { // if true then this will be the first subject to print
printf("\nSubjects:");
}
found = 1; // set flag
printf("Subject %d", j);
// the other printfs
}
}
if(!found) { // check flag
printf("No enrolled subjects.\n");
}
This replaces the whole
if(info[i].course[j].courseCode == 0){
...
} else {
...
}
block within the student loop.

Resources