# "C Primer Plus" programming exercises

## Chapter 14

### 1.exercise1.c

Design a structure template to store a month name, the 3-letter abbreviation of the month name, the number of days in the month, and the month number. Define an array containing 12 structures initialized to a year (not a leap year). Assume that the structure template and an array of the structure type are declared outside all functions. Write a function where the user provides a month number and the function returns the total number of days in the year up to and including that month. Use the spelling of the month name instead of the month number (don't forget to use strcmp()). Test the function in a simple program.

```//exercise14.1
#include <stdio.h>
#include <ctype.h>
#include <string.h>

struct month {
char name;
char abbrev;
int days;
int monumb;
};//structure template
const struct month months = {
{"January", "Jan", 31, 1},
{"February", "Feb", 28, 2},
{"March", "Mar", 31, 3},
{"April", "Apr", 30, 4},
{"May", "May", 31, 5},
{"June", "Jun", 30, 6},
{"July", "Jul", 31, 7},
{"August", "Aug", 31, 8},
{"September", "Sep", 30, 9},
{"October", "Oct", 31, 10},
{"November", "Nov", 3, 11},
{"December", "Dec", 31, 12}
};//array of structures
int days(char * input);//Get the name of the month and calculate the number of days
int main(void)
{
char input;
int total_days;

printf("Please enter the month name:(according to q exit the program)\n");
while (scanf("%s",input) == 1 && input != 'q')//Enter q to stop the loop
{
total_days = days(input);//Call functions
if (total_days > 0) //The total number of days is greater than 0, indicating that there is a corresponding month number
{
printf("The total number of days is:%d\n",total_days);
}
else
{
printf("There is a typo.\n");
}
printf("Please enter the name of the next month:(according to q exit the program)\n");
}
printf("end of program\n");

return 0;
}
int days(char * input)
{
int i;
int total = 0;
int num = 0;

input = toupper(input);//Convert the first letter to uppercase
for (i = 1; input[i] != '\0'; i++) //Loop until the input is converted to lowercase letters
{
input[i] = tolower(input[i]);
}
for (i = 0; i < 12; i++)
{
if (strcmp(input, months[i].name) == 0) //Compare with the name of each element of the structure array
{
num = months[i].monumb;//Find the corresponding month and assign the month number to num
break;
}
}
if (num == 0) //No corresponding month number
{
total = 0;
}
else
{
for (i = 0; i < num; i++) //corresponding month number
{
total += months[i].days;//to sum
}
}
}
```

Input example:

```Please enter the month name:(according to q exit the program)
febRuary
The total number of days is: 59
Please enter the name of the next month:(according to q exit the program)
q
end of program
```

### 2.exercise2.c

Write a function that prompts the user for the day, month, and year. Month can be a month number, a month name, or an abbreviated month name. The program should then return the total number of days in the year up to and including the day specified by the user.

```//exercise14.2
#include <stdio.h>
#include <ctype.h>
#include <string.h>

struct month {
char name;
char abbrev;
int days;
int monumb;
};//structure template
struct month months = {
{"January", "Jan", 31, 1},
{"February", "Feb", 28, 2},
{"March", "Mar", 31, 3},
{"April", "Apr", 30, 4},
{"May", "May", 31, 5},
{"June", "Jun", 30, 6},
{"July", "Jul", 31, 7},
{"August", "Aug", 31, 8},
{"September", "Sep", 30, 9},
{"October", "Oct", 31, 10},
{"November", "Nov", 3, 11},
{"December", "Dec", 31, 12}
};//array of structures
int days(int day, char * input);//Get the name of the month and calculate the number of days
void leapyear(int year);
int main(void)
{
int day, year;
char input;
int total_days;

printf("Please enter day, month, year:(according to q exit the program)\n");
while (scanf("%d %s %d", &day, input, &year) == 3 && input != 'q')
{
leapyear(year);
total_days = days(day, input);//Call functions
if (total_days > 0) //The total number of days is greater than 0, indicating that there is a corresponding month number
{
printf("The total number of days is:%d\n",total_days);
}
else
{
printf("There is a typo.\n");
}
months.days = 28;//Reset February to 28 days
printf("Please enter the next day, month and year:(according to q exit the program)\n");
}
printf("end of program\n");

return 0;
}
int days(int day, char * input)
{
int i;
int total = 0;
int num = 0;

input = toupper(input);//Convert the first letter to uppercase
for (i = 1; input[i] != '\0'; i++) //Loop until the input is converted to lowercase letters
{
input[i] = tolower(input[i]);
}
for (i = 0; i < 12; i++)
{
if (strcmp(input, months[i].name) == 0) //Compare with the name of each element of the structure array
{
num = months[i].monumb;//Find the corresponding month and assign the month number to num
break;
}
}
if (num == 0) //No corresponding month number
{
total = 0;
}
else
{
for (i = 0; i < num; i++) //corresponding month number
{
total += months[i].days;//to sum
}
total += day;//plus the number of days
}
}
void leapyear(int year)
{
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)//Determine whether it is a leap year
{
months.days = 29;//February is 29 days in a leap year
}
}
```

Example output:

```Please enter day, month, year:(according to q exit the program)
1 march 2020
The total number of days is: 92
Please enter the next day, month and year:(according to q exit the program)
1 march 2019
The total number of days is: 91
Please enter the next day, month and year:(according to q exit the program)
q
end of program
```

There is not too much input validation, the default is to follow the normal input.

### 3.exercise3.c

Modify the book catalog program in the program manybook.c so that it outputs book information in the order of input books, then outputs book information in alphabetical order of book titles, and finally outputs book information in ascending order of price.

```//exercise14.3
#include <stdio.h>
#include <string.h>

char * s_gets(char * st, int n);
#define MAXTITL   40
#define MAXAUTL   40
#define MAXBKS 100 /* maximum number of books */

struct book {                     /* Create a book template   */
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
void print(struct book library[MAXBKS], int count);//print as is
void print_al(struct book library[MAXBKS], int count);//print alphabetically
void print_price(struct book library[MAXBKS], int count);//Print in ascending order by price
int main(void)
{
struct book library[MAXBKS]; /* book array of structures of type */
int count = 0;

printf("Please enter the title of the book:\n");
printf("at start press enter key to end the program.\n");
while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL
&& library[count].title != '\0')
{
printf("Enter author name:\n");
s_gets(library[count].author, MAXAUTL);
printf("Enter the price of the book\n");
scanf("%f", &library[count++].value);
while (getchar() != '\n')
continue;          /* Clean up input lines  */
if (count < MAXBKS)
printf("Enter the name of the next book:\n");
}

if (count > 0)
{
printf("this is the order of your books:\n");
print(library, count);
print_al(library, count);
print_price(library, count);
}
else
printf("no books.\n");

return 0;
}

char * s_gets(char * st, int n)
{
char * ret_val;
char * find;

ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');   // find line breaks
if (find)                  // If the address is not NULL,
*find = '\0';          // put a null character here
else
while (getchar() != '\n')
continue;          // process the remaining characters in the input line
}
return ret_val;
}
void print(struct book library[MAXBKS], int count)
{
int index;

for (index = 0; index < count; index++)
{
printf("%s by %s: \$%.2f\n", library[index].title,
library[index].author, library[index].value);
}
}
void print_al(struct book library[MAXBKS], int count)
{
struct book temp;//mark
int index;
int i;

printf("Books output in alphabetical order:\n");
for (index = 0; index < count - 1; index++)//Bubble Sort
{
for (i = index + 1; i < count; i++)
{
if (strcmp(library[index].title, library[i].title) > 0)
//The letters of the later books are arranged in front of the earlier books
{
temp = library[index];//exchange
library[index] = library[i];
library[i] = temp;
}
}
}
print(library, count);//print the sorted
}
void print_price(struct book library[MAXBKS], int count)
{
struct book temp;
int index;
int i;

printf("Books are output in order of price:\n");
for (index = 0; index < count - 1; index++)
{
for (i = index + 1; i < count; i++)
{
if (library[index].value > library[i].value)
//Books in the front are more expensive than books in the back
{
temp = library[index];
library[index] = library[i];
library[i] = temp;
}
}
}
print(library, count);
}
```

Example output:

```Please enter the title of the book:
at start press enter key to end the program.
c study
Enter author name:
sttphen
Enter the price of the book
56
Enter the name of the next book:
python
Enter author name:
peter
Enter the price of the book
23
Enter the name of the next book:
java
Enter author name:
lily
Enter the price of the book
35
Enter the name of the next book:

this is the order of your books:
c study by sttphen: \$56.00
python by peter: \$23.00
java by lily: \$35.00
Books output in alphabetical order:
c study by sttphen: \$56.00
java by lily: \$35.00
python by peter: \$23.00
Books are output in order of price:
python by peter: \$23.00
java by lily: \$35.00
c study by sttphen: \$56.00
```

### 4.exercise4.c

Write a program that creates a struct template with two members:
a. The first member is the social security number, the second member is a structure with 3 members, the first member represents the first name, the second member represents the middle name, and the third member represents the last name. Create and initialize an array of 5 structures of this type. The program prints data in the following format:
Dribble, Flossie M. – 302039823
If there is a middle name, only the first letter of it is printed, followed by a dot (.); if there is no middle name, no dot is printed. Write a program to print, passing the array of structures to this function.
b. Modify part a to pass the value of the structure instead of the address of the structure.

```//exercise14.4a
#include <stdio.h>
#include <string.h>
#define LEN 20

struct names {
char fname[LEN];
char mname[LEN];
char lname[LEN];
};

struct message {
char sonum[LEN];
struct names name;
};
char * s_gets(char * st, int n);
void print(const struct message num[], int n);
int main(void)
{
struct message num;//array of structures
int count = 0;

printf("at start press enter key to end the program.\n");
while (count < 5 && s_gets(num[count].sonum, LEN) && num[count].sonum != '\0')
{//Enter no more than 5, or directly enter enter to exit
s_gets(num[count].name.fname, LEN);
s_gets(num[count].name.mname, LEN);
s_gets(num[count].name.lname, LEN);
if (count < 5)//Enter no more than 5, continue to enter
{
printf("Please enter the next insurance number:\n");
}
count++;
}
if (count > 0)//entered members
{
printf("Here are all the members:\n");
print(num, count);
}
else//No member entered
{
printf("There are no members.\n");
}
printf("The program ends.\n");

return 0;
}
char * s_gets(char * st, int n)
{
char * ret_val;
char * find;

ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');   // find line breaks
if (find)                  // If the address is not NULL,
*find = '\0';          // put a null character here
else
while (getchar() != '\n')
continue;          // process the remaining characters in the input line
}
return ret_val;
}
void print(const struct message num[], int n)
{
int i;

for (i = 0; i < n; i++)
{
if (num[i].name.mname == '\0')//middle name is empty
{
printf("%s,%s . -- %s\n", num[i].name.fname, num[i].name.lname, num[i].sonum);
}
else
{
printf("%s,%s %c. -- %s\n", num[i].name.fname, num[i].name.lname, num[i].name.mname, num[i].sonum);
}
}
}
```

Example output:

```Please enter the insurance number:
at start press enter key to end the program.
302039823
Dribble
Mit
Flossie
Please enter the next insurance number:
845145656
san

zhang
Please enter the next insurance number:
123456789
er
xiao
li
Please enter the next insurance number:
963852741
wu
xiao
wang
Please enter the next insurance number:
159263487
qi

tian
Please enter the next insurance number:
Here are all the members:
Dribble,Flossie M. -- 302039823
san,zhang . -- 845145656
er,li x. -- 123456789
wu,wang x. -- 963852741
qi,tian . -- 159263487
The program ends.
```
```//exercise14.4b
#include <stdio.h>
#include <string.h>
#define LEN 20

struct names {
char fname[LEN];
char mname[LEN];
char lname[LEN];
};

struct message {
char sonum[LEN];
struct names name;
};
char * s_gets(char * st, int n);
void print(const struct message nu);//transfer structure
int main(void)
{
struct message num;//array of structures
int count = 0;
int i;

printf("at start press enter key to end the program.\n");
while (count < 5 && s_gets(num[count].sonum, LEN) && num[count].sonum != '\0')
{//Enter no more than 5, or directly enter enter to exit
s_gets(num[count].name.fname, LEN);
s_gets(num[count].name.mname, LEN);
s_gets(num[count].name.lname, LEN);
if (count < 5)//Enter no more than 5, continue to enter
{
printf("Please enter the next insurance number:\n");
}
count++;
}
if (count > 0)//entered members
{
printf("Here are all the members:\n");
for (i = 0; i < count; i++)
{
print(num[i]);//print each member individually
}
}
else//No member entered
{
printf("There are no members.\n");
}
printf("The program ends.\n");

return 0;
}
char * s_gets(char * st, int n)
{
char * ret_val;
char * find;

ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');   // find line breaks
if (find)                  // If the address is not NULL,
*find = '\0';          // put a null character here
else
while (getchar() != '\n')
continue;          // process the remaining characters in the input line
}
return ret_val;
}
void print(const struct message nu)
{
if (nu.name.mname == '\0')//middle name is empty
{
printf("%s,%s . -- %s\n", nu.name.fname, nu.name.lname, nu.sonum);
}
else
{
printf("%s,%s %c. -- %s\n", nu.name.fname, nu.name.lname, nu.name.mname, nu.sonum);
}
}
```

### 5.exercise5.c

Write a program that satisfies the following requirements.
a. Externally define a structure template name with two members: a string to store the name, and a string to store the last name.
b. Externally define a structure template student with 3 members: a structure of name type, a grade array to store 3 floating-point scores, and a variable to store the average of 3 scores.
c. Declare an array containing CSIZE (CSIZE = 4) student type structures in the main() function, and initialize the name part of these structures. Use functions to perform the tasks described in d, e, f, and g.
d. Get each student's grade interactively, prompting the user to enter the student's name and grade. Store the score in the corresponding structure of the grade array. This can be done with a loop in the main() function or other functions.
e. Calculate the average score for each structure and assign the calculated value to the appropriate member.
f. Print the information for each structure.
g. Print the average score of the class, which is the average of all numerical members of the structure.

```//exercise14.5
#include <stdio.h>
#define CSIZE 4
#define LEN 20

struct name {
char surname[LEN];
char name[LEN];
};

struct student {
struct name na;
float average;
};

void get_grade(struct student stu[], int n);//Get scores for each student
void get_average(struct student stu[], int n);//Get the average score of each student
void print_student(struct student stu[], int n);//Print information for each student
void print_classarg(struct student stu[], int n);//Calculate class average and print
int main(void)
{
struct student stu[CSIZE] =
{
{"zhang", "san"},
{"li", "si"},
{"wang", "wu"},
{"tian", "qi"}

};//Initialize array of structures

get_average(stu, CSIZE);
print_student(stu, CSIZE);
print_classarg(stu, CSIZE);

return 0;
}
void get_grade(struct student stu[], int n)
{
int i, j;

for (i = 0; i < n; i++)
{
printf("please enter%s %s The three fractions of :\n", stu[i].na.surname, stu[i].na.name);
for (j = 0; j < 3; j++)
{
{
while (getchar() != '\n')
{
continue;
}
printf("Enter the next correct fraction:\n");
}
}
}
}
void get_average(struct student stu[], int n)
{
int i;

for (i = 0; i < n; i++)
{
}
}
void print_student(struct student stu[], int n)
{
int i;

printf("Below is information for all students:\n");
for (i = 0; i < n; i++)
{
printf("%s %s The three fractions of :%.1f %.1f %.1f，The average score:%.1f\n", stu[i].na.surname, stu[i].na.name
}
}
void print_classarg(struct student stu[], int n)
{
int i;
float total = 0.0;
float class_average;
printf("Class average score:");
for (i = 0; i < n; i++)
{
total += stu[i].average;
}
class_average = total / n;
printf("%.2f. \n", class_average);
}
```

Example output:

```please enter zhang san The three fractions of :
56 23 25
please enter li si The three fractions of :
23.5 62.5 23
please enter wang wu The three fractions of :
98 85 69
please enter tian qi The three fractions of :
98 97 96
Below is information for all students:
zhang san Three scores of: 56.0 23.0 25.0，Average score: 34.7
li si Three scores of: 23.5 62.5 23.0，Average score: 36.3
wang wu Three scores of: 98.0 85.0 69.0，Average score: 84.0
tian qi Three scores of: 98.0 97.0 96.0，Average score: 97.0
Class average score: 63.00.
```

### 6.exercise6.c

A text file holds information about a softball team. Each row of data is arranged like this:
4 Jessie Joybat 5 2 1 1
The first item is the player number, which ranges from 0 to 18 for convenience. Item 2 is the player's name. Item 3 is the player's last name. First name and last name are both one word. The fourth item is the official statistics of the number of times a player has played. The next three items are hits, walks and RBIs.
The file may contain data for multiple games, so there may be multiple lines for the same player, and there may be other players' data in between lines for the same player. Write a program to store data in an array of structures. The members of this structure represent the player's first name, last name, number of games played, number of hits, number of bases walked, RBI, and batting average (calculated later). You can use the player number as an index into the array. The program reads to the end of the file and counts the cumulative totals for each player.
World Baseball Statistics is relevant. For example, a turnover on a walk and a touch does not count toward the inning, but may result in an RBI. But what the program does is read and process the data file as described below, regardless of what the data actually means.
To achieve these functions, the easiest way is to initialize the contents of the structure to zero, read the data in the file into a temporary variable, and then add it to the corresponding structure. After the program has read the file, it should calculate the batting average for each player and store the result in the corresponding member of the structure. The batting average is calculated by dividing the player's cumulative hits by the cumulative number of previous games. This is a floating point calculation. Finally, the program combines the stats for the entire team, displaying a player's cumulative stats on one line.

```//exercise14.6
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LEN 19
typedef struct {
int id;
char name[LEN];
char surname[LEN];
int time;
int beat;
int walk;
int RBI;
float rate;
} TEAM; //define structure
static TEAM players[LEN];//Create an array of players, up to 19

int read_data(FILE * fp, TEAM players[], int n);//Get player information from the file and return the number of players
int get_rate(TEAM players[], int n);//Get the batting average for each player
void print(TEAM players[], int n);//print player information
void print_pre(FILE * fp);//Print file information
int main(void)
{
FILE * fp;
int line;

if ((fp = fopen("exercise6.txt", "r")) == NULL)//An error will be reported if the file fails to open, read mode
{
fprintf(stderr,"fail to open the file.\n");
exit(EXIT_FAILURE);
}
print_pre(fp);
rewind(fp);//Go to the beginning of the file
line = read_data(fp, players, LEN);//Call the function to execute the corresponding function
get_rate(players, line);
print(players, line);
if (fclose(fp) != 0)//Report an error when closing the file error
{
fprintf(stderr, "closure exercise6.txt fail.\n");
}
return 0;
}
void print_pre(FILE * fp)
{
int get_id, beat, time, walk, RBI;//Get the information corresponding to each row
char name[LEN];
char surname[LEN];

printf("Here is the data of the file:\n");
while (fscanf(fp, "%d %18s %18s %d %d %d %d", &get_id, name, surname, &time, &beat, &walk, &RBI) == 7
&& !feof(fp))
{
printf("%d %s %s %d %d %d %d\n", get_id, name, surname, time, beat, walk, RBI);//print file data
}
}
int read_data(FILE * fp, TEAM players[], int n)
{
int count = 0;//Count, used to get how many lines of data are stored in the file
int get_id, beat, time, walk, RBI;//Get the information corresponding to each row
char name[LEN];
char surname[LEN];
int temp[LEN] = {-1}; //Temporary array, storing the id of the player
int total;//Used for loop counting, array subscripts
int flag = 1;//Flag bit, indicating that the id that has been stored in the array has not been read
int temp_count = 0;//Return value, how many players are saved

while (fscanf(fp, "%d %18s %18s %d %d %d %d", &get_id, name, surname, &time, &beat, &walk, &RBI) == 7
&& !feof(fp) && count < n)
//feof() The feof() function returns a non-zero value when the previous input call detected end-of-file
{
for (total = 0;total < count + 1; total++)//Starting from 0, until the number of rows that have been read
{
if (temp[total] == get_id)//If the read id has been stored in the array
{
players[total].time += time;//Under the corresponding player, accumulate the corresponding playing times and other values ​​that need to be accumulated
players[total].beat += beat;
players[total].walk += walk;
players[total].RBI += RBI;
flag = 0;//The flag bit is assigned a value of 0, indicating that the player in this line of data has already been saved
break;//break out of the loop
}
}
if (flag == 1)//Indicates that this is a new player
{
players[temp_count].id = get_id;//Assign values ​​to the corresponding player structures
strcpy(players[temp_count].name,name);
strcpy(players[temp_count].surname,surname);
players[temp_count].time = time;
players[temp_count].beat = beat;
players[temp_count].walk = walk;
players[temp_count].RBI = RBI;
temp[temp_count] = get_id;
temp_count++;//New player, one is stored in the array, and the next array element is subscripted
}
flag = 1;//Reset to 1 to read the next line of data
}
return temp_count;//return number of players
}
int get_rate(TEAM players[], int n)
{
int i;

for (i = 0; i < n; i++)
{
players[i].rate = 1.0 *players[i].beat / players[i].time;
//This way the calculation will not be rounded and you will get a floating point number
}
}
void print(TEAM players[], int n)
{
int i;

if (n == 0)
{
printf("No player data.\n");
}
else
{
printf("Here is the player stats:\n");
for (i = 0; i < n; i++)
{
printf("%d %s %s %d %d %d %d %.2f\n",
players[i].id, players[i].name, players[i].surname, players[i].time,
players[i].beat, players[i].walk, players[i].RBI, players[i].rate);
}
}
}
```

Example output:

```Here is the data of the file:
4 Jessie Joybat 5 2 1 1
3 Jee Jot 6 3 2 1
6 Zhang san 6 3 2 1
3 Jee Jot 7 1 2 1
1 Lily Neo 10 3 6 2
Here is the player stats:
4 Jessie Joybat 5 2 1 1 0.40
3 Jee Jot 13 4 4 2 0.31
6 Zhang san 6 3 2 1 0.50
1 Lily Neo 10 3 6 2 0.30
```

### 7.exercise7.c

Modify the program booksave.c to read each record from the file and display it, allowing the user to delete the record or modify the content of the record. If a record is deleted, the vacated space is reserved for the next record to be read. To modify the content of an existing file, the "r+b" mode must be used instead of the "a+b" mode. Also, more attention must be paid to positioning the file pointers to prevent newly added records from overwriting existing ones. The easiest way is to change all the data stored in memory, and then write the final information to the file. One way to track this is to add a member to the book structure to indicate if the item was deleted.

```//exercise14.7
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTITL  40
#define MAXAUTL  40
#define MAXBKS 10 /* Maximum number of books */
char * s_gets(char * st, int n);
struct book {                   /* Create a book template */
char title[MAXTITL];
char author[MAXAUTL];
float value;
int is_delete;//Whether the mark is deleted, if yes, the value is 1
};
char get_char();//Get the entered information
void change(struct book * p);//Change a book's information
int main(void)
{
struct book library[MAXBKS]; //store books
int count = 0;
int index, filecount;
FILE * pbooks;
int size = sizeof (struct book);
char ch;//Get input options
struct book library_temp[MAXBKS]; //Temporary storage
int i = 0;

if ((pbooks = fopen("exercise7.txt", "r+")) == NULL)//r+ mode
{
fprintf(stderr, "Cannot open file.\n");
exit(EXIT_FAILURE);
}
rewind(pbooks);            /* Go to the beginning of the file */
while (count < MAXBKS &&  fread(&library[count], size, 1, pbooks) == 1)
if (count == 0)
{
puts("already in the file:");//First print the book information one by one
}
library[count].is_delete = 0;
printf("%s by %s: \$%.2f\n",library[count].title,library[count].author, library[count].value);

puts("Do you want to modify or delete this record? (to enter y，don't just type n)");
ch = get_char();//get y or n
if (ch == 'y')
{
puts("Modify record input y，Delete record input n: ");
ch = get_char();//continue to use this function
if (ch == 'y')
{
}
else
{
library[count].is_delete = 1;//This book is deleted and the mark is set to 1
printf("%s by %s The file has been deleted.\n", library[count].title, library[count].author);
}
}
}
filecount = count;//The total number of books read in the file
if (count == MAXBKS)//equal to the maximum number
{
fputs("exercise7.txt The space is full.", stderr);
exit(EXIT_FAILURE);//quit
}
puts("Enter a new book title (press enter at the beginning of a line to exit):");
while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL
&& library[count].title != '\0')
{
library[count].is_delete = 0;//First assign a value to the deletion mark of the book
puts("Enter author name:");
s_gets(library[count].author, MAXAUTL);
puts("Enter the price of the book:");
scanf("%f", &library[count].value);
count++;//The total number of books +1, including those already stored in the file
while (getchar() != '\n')
continue;
if (count < MAXBKS)
puts("Enter the title of the next book:");
}
if (count > 0)
{
puts("Here is the list of books:");
for (index = 0; index < count; index++)
{//Print all books in a loop
if (library[index].is_delete == 0)//Books that are not deleted are printed
{
printf("%s by %s: \$%.2f\n",library[index].title,library[index].author, library[index].value);
}
}
for (index = 0; index < count; index++)//Books that are not deleted are stored in a temporary structure
{
if (library[index].is_delete == 0)
{
library_temp[i] = library[index];
i++;//+1 for storing in temporary structure
}
}
for (index = 0; index < i; index++)
{
library[index] = library_temp[index];
//Then put the temporary structure in the static structure, the next time you run the program to read the book
}
if (fclose(pbooks) != 0)//close the file
{
fprintf(stderr, "Failed to close file.\n");
exit(EXIT_FAILURE);
}
if ((pbooks = fopen("exercise7.txt", "w")) == NULL)//Open the file again in write mode
{
fprintf(stderr, "fail to open the file.\n");
exit(EXIT_FAILURE);
}
for (index = 0; index < i; index++)
{//Store remaining books in file
fwrite(&library[index], size, 1, pbooks);//Write the books that are not deleted one by one to the file
}
}
else
{
puts("no books.\n");
}
if (fclose(pbooks) != 0)
{
fprintf(stderr, "Failed to close file.\n");
exit(EXIT_FAILURE);
}
puts("The program ends.");

return 0;
}
char * s_gets(char * st, int n)
{
char * ret_val;
char * find;

ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
char get_char()
{
char temp;//The input is temporarily stored in this array

while (s_gets(temp, 10) == NULL || (temp != 'y' && temp != 'n') || temp != '\0')
{//The input is empty or the first character entered is not one of y, n or the second character is not a newline
puts("please enter y or n. ");
}
return temp;//return y or n
}
void change(struct book * p)
{
puts("Enter the modified book title (press enter at the beginning of a line to exit):");
s_gets(p->title, MAXAUTL);
puts("Enter the modified author name:");
s_gets(p->author, MAXAUTL);
puts("Enter the revised book price:");
scanf("%f", &p->value);
while (getchar() != '\n')
{
continue;
}
}
```

Run the program for the first time and add two books:

```Enter a new book title (press enter at the beginning of a line to exit):
c
Enter author name:
zhangsan
Enter the price of the book:
11
Enter the title of the next book:
c++
Enter author name:
lisi
Enter the price of the book:
22
Enter the title of the next book:

Here is the list of books:
c by zhangsan: \$11.00
c++ by lisi: \$22.00
The program ends.
```

Run the program a second time to add three more books:

```already in the file:
c by zhangsan: \$11.00
Do you want to modify or delete this record? (to enter y，don't just type n)
n
c++ by lisi: \$22.00
Do you want to modify or delete this record? (to enter y，don't just type n)
n
Enter a new book title (press enter at the beginning of a line to exit):
java
Enter author name:
wangwu
Enter the price of the book:
33.5
Enter the title of the next book:
python
Enter author name:
maliu
Enter the price of the book:
44.5
Enter the title of the next book:
c#
Enter author name:
tianqi
Enter the price of the book:
66.2
Enter the title of the next book:

Here is the list of books:
c by zhangsan: \$11.00
c++ by lisi: \$22.00
java by wangwu: \$33.50
python by maliu: \$44.50
c# by tianqi: \$66.20
```

Run the program a third time, modifying a book:

```already in the file:
c by zhangsan: \$11.00
Do you want to modify or delete this record? (to enter y，don't just type n)
y
Modify record input y，Delete record input n:
y
Enter the modified book title (press enter at the beginning of a line to exit):
c++++
Enter the modified author name:
zhaojiu
Enter the revised book price:
77
c++ by lisi: \$22.00
Do you want to modify or delete this record? (to enter y，don't just type n)
n
java by wangwu: \$33.50
Do you want to modify or delete this record? (to enter y，don't just type n)
n
python by maliu: \$44.50
Do you want to modify or delete this record? (to enter y，don't just type n)
n
c# by tianqi: \$66.20
Do you want to modify or delete this record? (to enter y，don't just type n)
n
Enter a new book title (press enter at the beginning of a line to exit):

Here is the list of books:
c++++ by zhaojiu: \$77.00
c++ by lisi: \$22.00
java by wangwu: \$33.50
python by maliu: \$44.50
c# by tianqi: \$66.20
The program ends.
```

Delete two books:

```already in the file:
c++++ by zhaojiu: \$77.00
Do you want to modify or delete this record? (to enter y，don't just type n)
n
c++ by lisi: \$22.00
Do you want to modify or delete this record? (to enter y，don't just type n)
y
Modify record input y，Delete record input n:
n
c++ by lisi The file has been deleted.
java by wangwu: \$33.50
Do you want to modify or delete this record? (to enter y，don't just type n)
n
python by maliu: \$44.50
Do you want to modify or delete this record? (to enter y，don't just type n)
y
Modify record input y，Delete record input n:
n
python by maliu The file has been deleted.
c# by tianqi: \$66.20
Do you want to modify or delete this record? (to enter y，don't just type n)
n
Enter a new book title (press enter at the beginning of a line to exit):

Here is the list of books:
c++++ by zhaojiu: \$77.00
java by wangwu: \$33.50
c# by tianqi: \$66.20
The program ends.
```

Run it again to see:

```already in the file:
c++++ by zhaojiu: \$77.00
Do you want to modify or delete this record? (to enter y，don't just type n)
n
java by wangwu: \$33.50
Do you want to modify or delete this record? (to enter y，don't just type n)
n
c# by tianqi: \$66.20
Do you want to modify or delete this record? (to enter y，don't just type n)
n
Enter a new book title (press enter at the beginning of a line to exit):

Here is the list of books:
c++++ by zhaojiu: \$77.00
java by wangwu: \$33.50
c# by tianqi: \$66.20
The program ends.
```

The input verification is not perfect; it is not good to prompt the user whether to modify or delete one book after another. You should print all the books, then enter the name of the book to match, and then modify and delete. This is more reasonable. But the amount of code has increased a lot, and it will be left for the follow-up.

Creating a temporary structure to store the remaining books is actually relatively inefficient. You should use a linked list. After deleting a book, point the pointer of the previous book to the book behind the deleted book, which belongs to the content of the data structure. , for later.

### 8.exercise8.c

Giant Airlines' fleet consists of 12-seat aircraft. It flies one flight a day. According to the following requirements, write a seat reservation program.
a. The program uses an array of 12 structures. Each structure includes: a member represents the seat number, a member represents whether the seat has been reserved, a member represents the first name of the person who made the reservation, and a member represents the last name of the person who made the reservation.
b. The program displays the following menu:
To choose a function, enter its letter label:
a)Show number of empty seats a) Show number of empty seats
b)Show list of empty seats b) Show list of empty seats
c)Show alphabetical list of seats c) Show alphabetical list of seats
d) Assign a customer to a seat assignment d) Assign a seat to a customer
e) Delete a seat assignment e) Delete an already assigned seat
f) Quit f) Quit

c. The program can successfully execute the menu given above. Choose d) and e) to prompt the user for additional input, and each option allows the user to abort the input.
d. After executing a particular program, the program displays the menu again unless the user selects f).

```//exercise14.8
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SEAT 12
#define LEN 20
struct planes {
int id;
int is_book;
char fname[LEN];
char lname[LEN];
};
char get_char();//Get the menu options entered
char * s_gets(char * st, int n);
int a_num(const struct planes plane[], int n);
void b_list(const struct planes plane[], int n);
void c_show(const struct planes plane[], int n);
void d_assign(struct planes *plane, int n);
void no_assign(const struct planes plane[], int n, int *arr);
int get_id(int *arr, int n);
void e_delete(struct planes *plane, int n);
void is_assign(const struct planes plane[], int n, int *arr);
int main(void)
{
struct planes plane[SEAT];
char choice;
FILE *fp;
int size = sizeof(struct planes);
int i;
int empty;

if ((fp = fopen("exercise8.txt", "r+")) == NULL)//read-write mode on
{
fprintf(stderr,"open a file exercise8.txt fail\n");
exit(EXIT_FAILURE);
}
if (fgetc(fp) == EOF)
{/*Read the file first, if the file is empty, that is, the first time you run the program
int fgetc(FILE *stream)Get the next character (an unsigned char) from the specified stream
，And move the position identifier forward, if it reaches the end of the file or a read error occurs, return EOF*/
for (i = 0; i < SEAT; i++)//First number the 12 seats 1-12, and then they are all unreserved
{
plane[i].id = i + 1;
plane[i].is_book = 0;//seat not reserved
}
fwrite(plane, size, SEAT, fp);//Number the 12 seats and write them all into the file
}//This paragraph will only be executed when the program is run for the first time, and the following files will have content
rewind(fp);//back to beginning of file
fread(plane, size, SEAT, fp);//Read the contents of the file into an array of structures
if (ferror(fp) != 0)
{
fprintf(stderr, "write to file exercise8.txt fail,\n");
exit(EXIT_FAILURE);
}

choice = get_char();//get options
while (choice != 'f')//If the input is not f, it keeps looping
{
switch (choice)
{
case 'a':
printf("A total of%d empty seat.\n", a_num(plane, SEAT));
break;
case 'b':
b_list(plane, SEAT);
break;
case 'c':
c_show(plane, SEAT);
break;
case 'd':
d_assign(plane, SEAT);
break;
case 'e':
e_delete(plane, SEAT);
break;
default:
printf("Something went wrong with the program.\n");
break;
}
choice = get_char();
}
if (fclose(fp) != 0)//close file
{
fprintf(stderr, "close file exercise8.txt fail,\n");
exit(EXIT_FAILURE);
}
if ((fp = fopen("exercise8.txt", "w")) == NULL)//write mode on
{
fprintf(stderr,"open a file exercise8.txt fail\n");
exit(EXIT_FAILURE);
}
fwrite(plane, size, SEAT, fp);
//Rewrite the changed seat information back to the file, and the next time you open the program, the results after the last program run will be retained
if (ferror(fp) != 0)
{
fprintf(stderr, "write to file exercise8.txt fail,\n");
exit(EXIT_FAILURE);
}
if (fclose(fp) != 0)
{
fprintf(stderr, "close file exercise8.txt fail,\n");
exit(EXIT_FAILURE);
}
puts("The program ends.");

return 0;
}
{
printf("To select a function, enter the corresponding letters:\n");
printf("a)Show the number of empty seats\n");
printf("b)Show list of available seats\n");
printf("c)Display Seat List Alphabetically\n");
printf("d)Assign seats to customers\n");
printf("e)delete an assigned seat\n");
printf("f)quit\n");
}
char get_char()
{
char temp;//The input is temporarily stored in this array

while (s_gets(temp, 3) == NULL || temp != '\0' || temp > 'f' || temp < 'a')
{//If the input is not a single letter, or a letter that is not between a-f, enter it in a loop
}
return temp;//Returns the options entered
}
char * s_gets(char * st, int n)//input string
{
char * ret_val;
char * find;

ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
int a_num(const struct planes plane[], int n)//a function, showing how many vacant seats there are
{
int i;
int count = 0;//empty seat count

for (i = 0; i < n; i++)
{
if (plane[i].is_book == 0)//Seat reservation mark is 0, it is an empty seat
{
count++;
}
}
return count;
}
void b_list(const struct planes plane[], int n)//b function, display the number of unreserved seats
{
int i;
int count;//empty seat count

count = a_num(plane, n);
if (count == 0)
{
printf("There are no empty seats.\n");
}
else
{
printf("%d Number of empty seats:", count);
for (i = 0; i < n; i++)
{
if (plane[i].is_book == 0)//seat is empty
{
printf("%d ", plane[i].id);
}
}
printf("\n");
}
}
void c_show(const struct planes plane[], int n)//c function, sorted and displayed in the order of name
{
struct planes temp;//temporary structure
struct planes temp_plane[n];//array of temporary structures
int i, j;
int top;
int count = 0;

if (a_num(plane, n) == SEAT)
{
printf("All empty seats.\n");
}
else
{
for (i = 0; i < n; i++)//assignment
{
if (plane[i].is_book == 1)//is a reserved seat
{
temp_plane[count] = plane[i];//store in temporary structure array
count++;//Temporary structure array storage seat +1
}
}
for (i = 0; i < count; i++)//Bubble Sort Temporary Structure Array
{
for (top = i + 1; top < count; top++)//inner loop
{
if (strcmp(temp_plane[i].fname, temp_plane[top].fname) > 0)
//Comparing the order of the first names of two seat bookers
{
temp = temp_plane[i];//is the exchange order
temp_plane[i] = temp_plane[top];
temp_plane[top] =temp;
}
}
}
printf("Below is an alphabetical list of seats:\n");
for (i = 0; i < count; i++)
{
printf("%d %d %s %s\n",
temp_plane[i].id, temp_plane[i].is_book, temp_plane[i].fname, temp_plane[i].lname);
}
}
}
void d_assign(struct planes *plane, int n)//d function, reserve a seat
{
int arr[n];//store empty seats
int getid;//Get the seat number you want to book
int i;

if (a_num(plane, n) == 0)
{
printf("There are no empty seats.\n");
}
else
{
no_assign(plane, SEAT, arr);//Call this function to store the number of the empty seat in the array storing the empty seat
printf("Please enter the seat number you want to choose:");
getid = get_id(arr, n);//Get the seat number you want to book
while (getid == 0)//This is not an empty seat, choose another seat
{
printf("Please enter the unreserved seat number:");
getid = get_id(arr, n);
}
s_gets(plane[getid - 1].fname, n);
s_gets(plane[getid - 1].lname, n);
plane[getid - 1].is_book = 1;//Mark this seat successfully reserved
}
}
void no_assign(const struct planes plane[], int n, int *arr)//unreserved seat
{
int i;

for (i = 0; i < n; i++)
{
if (plane[i].is_book == 0)//seat not reserved
{
arr[i] = plane[i].id;//exists in the array of empty seats
}
}
}
int get_id(int *arr, int n)//Get the number entered
{
int input;
int i;

while (scanf("%d", &input) != 1 || getchar() != '\n' || input > 12 || input < 1)
{//If the input is not a number or the number is not in 1-12, loop input
printf("Please enter the correct number:", input);
while (getchar() != '\n')
{
continue;
}
}
for (i = 0; i < n; i++)
{
if (input == arr[i])//The input value is compared with the value in the array one by one, if it is satisfied, the input is valid
{
return input;//returns this effective value
}
}
return 0;
}
void e_delete(struct planes *plane, int n)//e function, delete a seat reservation information
{
int arr[n];//array of reserved seats
int getid;
int i;

if (a_num(plane, n) == SEAT)
{
printf("All empty seats.\n");
return;
}
else
{
is_assign(plane, SEAT, arr);
printf("Please enter the seat number you want to delete:");
getid = get_id(arr, n);
while (getid == 0)
{
printf("Please enter the reserved seat number:");
getid = get_id(arr, n);
}
strcpy(plane[getid - 1].fname, "");//Delete seat information
strcpy(plane[getid - 1].lname, "");
plane[getid - 1].is_book = 0;//The seat is marked as an empty seat, and the seat is deleted successfully
}
}
void is_assign(const struct planes plane[], int n, int *arr)//reserved seat
{

int i;

for (i = 0; i < n; i++)
{
if (plane[i].is_book == 1)//seat reserved
{
arr[i] = plane[i].id;//exists in the predetermined array
}
}
}
```

The first time you run the program, the empty exercise8.txt file will be filled with 12 seat information, showing the b function:

```To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)quit
b
9 Number of empty seats: 1 3 4 6 7 9 10 11 12
To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)quit
f
The program ends.
```

Run the program for the second time, reserve three seats, and display the d function:

```To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)quit
b
12 Number of empty seats: 1 2 3 4 5 6 7 8 9 10 11 12
To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)quit
d
Please enter the seat number you want to choose: 2
To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)quit
d
Please enter the seat number you want to choose: 5
To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)quit
d
Please enter the seat number you want to choose: 8
To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)quit
f
The program ends.
```

Run the program for the third time to display the functions of a, c, and e:

```To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)quit
a
There are 9 empty seats in total.
To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)quit
c
Below is an alphabetical list of seats:
8 1 liu ma
2 1 san zhang
5 1 si li
To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)quit
e
Please enter the seat number you want to delete: 2
To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)quit
c
Below is an alphabetical list of seats:
8 1 liu ma
5 1 si li
To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)quit
f
The program ends.
```

You can use the fgetc() function to determine whether the file is empty, and then fill the empty file; when you need to modify the content of the structure array itself, you must pass in the pointer, otherwise you can pass in the structure array, and you must add a const qualifier to prevent the content from being tampered with ;The input verification is not done well, because when using the d function, the modification has to be completed. It is not possible to terminate this function halfway and return to the menu. It should prompt q to terminate this function. This must use a function to determine the input content, and no solution has been found for the time being.

### 9.exercise9.c

Giant Airlines (programming exercise 8) needs another plane (same capacity) and flies 4 times a day (flights 102, 311, 444 and 519). Extend the program to handle 4 flights. Provide flight selection and exit with a top-level menu. Selecting a specific flight brings up a menu similar to programming exercise 8. But the menu will add a new option: Confirm seat assignment. Moreover, the exit in the menu is to return to the top menu. Each display should indicate the flight number currently being processed. In addition, the seat assignment display shall indicate the confirmation status.

```//exercise14.9
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LEN 20
#define SEAT 12

struct planes {
int id;
int is_book;
char fname[LEN];
char lname[LEN];
};

char get_char();//Get the menu options entered
char * s_gets(char * st, int n);//input string
void airlane_menu();//After entering the flight, select the corresponding function
void plane_deal(char choice);//Go to the appropriate flight handler
int a_num(const struct planes plane[], int n);//a function, showing how many empty seats there are
void b_list(const struct planes plane[], int n);//b function, display the number of unreserved seats
void c_show(const struct planes plane[], int n);//c function, sorted and displayed in the order of name
void d_assign(struct planes *plane, int n);//d function, reserve a seat
void no_assign(const struct planes plane[], int n, int *arr); //unreserved seat
int get_id(int *arr, int n);//Get the number entered
void e_delete(struct planes *plane, int n);//e function, delete a seat reservation information
void is_assign(const struct planes plane[], int n, int *arr);//reserved seat
void f_confirm(const struct planes plane[], int n); //f function to display the seat assigned
int main(void)
{
char choice;

choice = get_char();//get options
while (choice != 'e')
{
if (choice < 'a' || choice > 'e')
{
choice = get_char();
break;
}
plane_deal(choice);//Enter the corresponding flight
choice = get_char();//get options
}

puts("The program ends.");
return 0;
}
char get_char()
{
char temp;//The input is temporarily stored in this array

while (s_gets(temp, 3) == NULL || temp != '\0' || temp > 'z' || temp < 'a')
{//If the input is not a single letter, or a letter that is not between a-f, enter it in a loop
}
return temp;//Returns the options entered
}
char * s_gets(char * st, int n)//input string
{
char * ret_val;
char * find;

ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
{
puts("a)102    b)311    c)444    d)519    e)exit the program");
printf("To select a flight, enter the corresponding letters:");
}
void plane_deal(char choice)
{
char filename[LEN];//File name, store the corresponding flight
FILE *fp;
struct planes plane[SEAT];
int size = sizeof(struct planes);
int i;
int empty;
char choice_two;
int num;//store flight number

switch (choice)
{
case 'a':
puts("The following is flight 102:");
num = 102;//Flight 120
strcpy(filename, "exercise9a.txt");//102 flight information is stored in the corresponding file
break;
case 'b':
puts("The following is flight 311:");
num = 311;
strcpy(filename, "exercise9b.txt");
break;
case 'c':
puts("The following is flight 444:");
num = 444;
strcpy(filename, "exercise9c.txt");
break;
case 'd':
puts("The following is flight 519:");
num = 519;
strcpy(filename, "exercise9d.txt");
break;
default:
printf("Something went wrong with the program.\n");
break;
}
if ((fp = fopen(filename, "r+")) == NULL)//Open the corresponding file in read-write mode
{
fprintf(stderr,"open a file%s.fail\n", filename);
exit(EXIT_FAILURE);
}
if (fgetc(fp) == EOF)
{/*Read the file first, if the file is empty, that is, the first time you run the program
int fgetc(FILE *stream)Get the next character (an unsigned char) from the specified stream
，And move the position identifier forward, if it reaches the end of the file or a read error occurs, return EOF*/
for (i = 0; i < SEAT; i++)//First number the 12 seats 1-12, and then they are all unreserved
{
plane[i].id = i + 1;
plane[i].is_book = 0;//seat not reserved
}
fwrite(plane, size, SEAT, fp);//Number the 12 seats and write them all into the file
}//This paragraph will only be executed when the program is run for the first time, and the following files will have content
rewind(fp);//back to beginning of file
fread(plane, size, SEAT, fp);//Read the contents of the file into an array of structures
if (ferror(fp) != 0)
{
fprintf(stderr, "write to file%s fail.\n", filename);
exit(EXIT_FAILURE);
}
choice_two = get_char();//get options
while (choice_two != 'g')//If the input is not g, it will keep looping in this flight
{
if (choice_two < 'a' || choice_two > 'g')
{
choice_two = get_char();
break;
}
switch (choice_two)
{
case 'a':
printf("A total of%d empty seat.\n", a_num(plane, SEAT));
break;
case 'b':
b_list(plane, SEAT);
break;
case 'c':
c_show(plane, SEAT);
break;
case 'd':
d_assign(plane, SEAT);
break;
case 'e':
e_delete(plane, SEAT);
break;
case 'f':
f_confirm(plane, SEAT);
break;
default:
printf("Something went wrong with the program.\n");
break;
}
printf("The following is%d flight:", num);//Prompt user is still operating on this flight
choice_two = get_char();
}
if (fclose(fp) != 0)//Close the file corresponding to the flight
{
fprintf(stderr, "close file%s fail,\n", filename);
exit(EXIT_FAILURE);
}
if ((fp = fopen(filename, "w")) == NULL)//write mode on
{
fprintf(stderr,"open a file%s fail\n", filename);
exit(EXIT_FAILURE);
}
fwrite(plane, size, SEAT, fp);
//Rewrite the changed seat information back to the file, and the next time you open the program, the results after the last program run will be retained
if (ferror(fp) != 0)
{
fprintf(stderr, "write to file%s fail,\n", filename);
exit(EXIT_FAILURE);
}
if (fclose(fp) != 0)
{
fprintf(stderr, "close file%s fail,\n", filename);
exit(EXIT_FAILURE);
}
}
{
printf("To select a function, enter the corresponding letters:\n");
printf("a)Show the number of empty seats\n");
printf("b)Show list of available seats\n");
printf("c)Display Seat List Alphabetically\n");
printf("d)Assign seats to customers\n");
printf("e)delete an assigned seat\n");
printf("f)Confirm seat assignment\n");
printf("g)quit\n");
}
int a_num(const struct planes plane[], int n)//a function, showing how many vacant seats there are
{
int i;
int count = 0;//empty seat count

for (i = 0; i < n; i++)
{
if (plane[i].is_book == 0)//Seat reservation mark is 0, it is an empty seat
{
count++;
}
}
return count;
}
void b_list(const struct planes plane[], int n)//b function, display the number of unreserved seats
{
int i;
int count;//empty seat count

count = a_num(plane, n);
if (count == 0)
{
printf("There are no empty seats.\n");
}
else
{
printf("%d Number of empty seats:", count);
for (i = 0; i < n; i++)
{
if (plane[i].is_book == 0)//seat is empty
{
printf("%d ", plane[i].id);
}
}
printf("\n");
}
}
void c_show(const struct planes plane[], int n)//c function, sorted and displayed in the order of name
{
struct planes temp;//temporary structure
struct planes temp_plane[n];//array of temporary structures
int i, j;
int top;
int count = 0;

if (a_num(plane, n) == SEAT)
{
printf("All empty seats.\n");
}
else
{
for (i = 0; i < n; i++)//assignment
{
if (plane[i].is_book == 1)//is a reserved seat
{
temp_plane[count] = plane[i];//store in temporary structure array
count++;//Temporary structure array storage seat +1
}
}
for (i = 0; i < count; i++)//Bubble Sort Temporary Structure Array
{
for (top = i + 1; top < count; top++)//inner loop
{
if (strcmp(temp_plane[i].fname, temp_plane[top].fname) > 0)
//Comparing the order of the first names of two seat bookers
{
temp = temp_plane[i];//is the exchange order
temp_plane[i] = temp_plane[top];
temp_plane[top] =temp;
}
}
}
printf("Below is an alphabetical list of seats:\n");
for (i = 0; i < count; i++)
{
printf("%d %d %s %s\n",
temp_plane[i].id, temp_plane[i].is_book, temp_plane[i].fname, temp_plane[i].lname);
}
}
}
void d_assign(struct planes *plane, int n)//d function, reserve a seat
{
int arr[n];//store empty seats
int getid;//Get the seat number you want to book
int i;

if (a_num(plane, n) == 0)
{
printf("There are no empty seats.\n");
}
else
{
no_assign(plane, SEAT, arr);//Call this function to store the number of the empty seat in the array storing the empty seat
printf("Please enter the seat number you want to choose:");
getid = get_id(arr, n);//Get the seat number you want to book
while (getid == 0)//This is not an empty seat, choose another seat
{
printf("Please enter the unreserved seat number:");
getid = get_id(arr, n);
}
s_gets(plane[getid - 1].fname, n);
s_gets(plane[getid - 1].lname, n);
plane[getid - 1].is_book = 1;//Mark this seat successfully reserved
}
}
void no_assign(const struct planes plane[], int n, int *arr)//unreserved seat
{
int i;

for (i = 0; i < n; i++)
{
if (plane[i].is_book == 0)//seat not reserved
{
arr[i] = plane[i].id;//exists in the array of empty seats
}
}
}
int get_id(int *arr, int n)//Get the number entered
{
int input;
int i;

while (scanf("%d", &input) != 1 || getchar() != '\n' || input > 12 || input < 1)
{//If the input is not a number or the number is not in 1-12, loop input
printf("Please enter the correct number:", input);
while (getchar() != '\n')
{
continue;
}
}
for (i = 0; i < n; i++)
{
if (input == arr[i])//The input value is compared with the value in the array one by one, if it is satisfied, the input is valid
{
return input;//returns this effective value
}
}
return 0;
}
void e_delete(struct planes *plane, int n)//e function, delete a seat reservation information
{
int arr[n];//array of reserved seats
int getid;
int i;

if (a_num(plane, n) == SEAT)
{
printf("All empty seats.\n");
return;
}
else
{
is_assign(plane, SEAT, arr);
printf("Please enter the seat number you want to delete:");
getid = get_id(arr, n);
while (getid == 0)
{
printf("Please enter the reserved seat number:");
getid = get_id(arr, n);
}
strcpy(plane[getid - 1].fname, "");//Delete seat information
strcpy(plane[getid - 1].lname, "");
plane[getid - 1].is_book = 0;//The seat is marked as an empty seat, and the seat is deleted successfully
}
}
void is_assign(const struct planes plane[], int n, int *arr)//reserved seat
{

int i;

for (i = 0; i < n; i++)
{
if (plane[i].is_book == 1)//seat reserved
{
arr[i] = plane[i].id;//exists in the predetermined array
}
}
}
void f_confirm(const struct planes plane[], int n)//f function to display the seat assigned
{
int i;

puts("Allocated Seats:");
for (i = 0; i < n; i++)
{
if (plane[i].is_book == 1)//Seat reservation mark is 0, it is allocated seat
{
printf("%d %d %s %s\n",
plane[i].id, plane[i].is_book, plane[i].fname, plane[i].lname);
}
}
}
```

Make modifications on the basis of programming exercise 8, and put the information of 4 flights in 4 different files, namely exercise9a.txt, exercise9b.txt, exercise9c.txt, exercise9d.txt The first run:

```a)102    b)311    c)444    d)519    e)exit the program
To select a flight, enter the corresponding letters: a
The following is flight 102:
To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)Confirm seat assignment
g)quit
f
All empty seats.
Here is Flight 102: To select a function, enter the corresponding letter:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)Confirm seat assignment
g)quit
d
Please enter the seat number you want to choose: 5
Here is Flight 102: To select a function, enter the corresponding letter:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)Confirm seat assignment
g)quit
g
a)102    b)311    c)444    d)519    e)exit the program
To select a flight, enter the corresponding letters: b
The following is flight 311:
To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)Confirm seat assignment
g)quit
d
Please enter the seat number you want to choose: 5
Here is Flight 311: To select a function, enter the corresponding letter:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)Confirm seat assignment
g)quit
d
Please enter the seat number you want to choose: 9
Here is Flight 311: To select a function, enter the corresponding letter:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)Confirm seat assignment
g)quit
c
Below is an alphabetical list of seats:
9 1 liu ma
5 1 si li
Here is Flight 311: To select a function, enter the corresponding letter:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)Confirm seat assignment
g)quit
g
a)102    b)311    c)444    d)519    e)exit the program
To select a flight, enter the corresponding letters: f
Please enter the correct letter: e
The program ends.
```

For the second run, you can also read the data after the last run:

```a)102    b)311    c)444    d)519    e)exit the program
To select a flight, enter the corresponding letters: b
The following is flight 311:
To select a function, enter the corresponding letters:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)Confirm seat assignment
g)quit
f
Allocated Seats:
5 1 si li
9 1 liu ma
Here is Flight 311: To select a function, enter the corresponding letter:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)Confirm seat assignment
g)quit
e
Please enter the seat number you want to delete: 5
Here is Flight 311: To select a function, enter the corresponding letter:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)Confirm seat assignment
g)quit
f
Allocated Seats:
9 1 liu ma
Here is Flight 311: To select a function, enter the corresponding letter:
a)Show the number of empty seats
b)Show list of available seats
c)Display Seat List Alphabetically
d)Assign seats to customers
e)delete an assigned seat
f)Confirm seat assignment
g)quit
g
a)102    b)311    c)444    d)519    e)exit the program
To select a flight, enter the corresponding letters: e
The program ends.
```

### 10.exercise10.c

Write a program to realize the menu through an array of function pointers. For example, selecting a in the menu will activate the function pointed to by the first element of the array.

```//exercise14.10
#include <stdio.h>
#include <string.h>
#define LEN 2

void show(void (*pf)(int, int), int x, int y);
void a_f(int x, int y);
void b_f(int x, int y);
char get_char(void);
char * s_gets(char * st, int n);
int main(void)
{
char ch;
void (*pf[LEN])(int, int);//array of function pointers
int x, y;

while (scanf("%d %d", &x, &y) != 2)
{
while (getchar() != '\n')
{
continue;
}
}
while (getchar() != '\n')
{
continue;
}
puts("Please enter the appropriate option to select the function.");
ch = get_char();
while (ch != 'c')
{
switch(ch)
{
case 'a':
pf = a_f;//pointer assignment
show(pf, x, y);//Call functions
break;
case 'b':
pf = b_f;
show(pf, x, y);
break;
default:
printf("Program error.\n");
break;
}
puts("Please enter the appropriate option to select the function.");
ch = get_char();
}
puts("Please enter the appropriate option to select the function.");
return 0;
}
{
puts("Please enter the appropriate option to select the function.");
puts("a)Calculates the sum of two integers");
puts("b)Computes the difference between two integers");
puts("c)quit");
}
void a_f(int x, int y)
{
printf("%d + %d = %d\n", x, y, x + y);
}
void b_f(int x, int y)
{
printf("%d - %d = %d\n", x, y, x - y);
}
char get_char(void)
{
char temp;//The input is temporarily stored in this array

while (s_gets(temp, 3) == NULL || temp != '\0' || temp > 'c' || temp < 'a')
{//If the input is not a single letter, or a letter that is not between a-f, enter it in a loop
}
return temp;//Returns the options entered
}
char * s_gets(char * st, int n)//input string
{
char * ret_val;
char * find;

ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
void show(void (*pf)(int, int), int x, int y)
{
(*pf)(x, y);//Calling a function using a function pointer
}
```

Example output:

```Please enter the appropriate option to select the function.
a)Calculates the sum of two integers
b)Computes the difference between two integers
c)quit
5 6
Please enter the appropriate option to select the function.
a
5 + 6 = 11
Please enter the appropriate option to select the function.
b
5 - 6 = -1
Please enter the appropriate option to select the function.
c
The program ends.
```

Simple demonstration, pay attention to the corresponding parameters when declaring the function pointer.

### 11.exercise11.c

Write a function called transform() that accepts 4 parameters: the source array name containing double type data, the target array name containing double type data, an int type parameter representing the number of array elements, the function name (or Equivalent function pointer). The transform() function shall apply the specified function to each element in the source array and store the return value in the destination array. For example:
transform(source, target, 100, sin);
This statement would set target to sin(source), etc., for a total of 100 elements. Call transform()4 times in a program to test the function. Use two functions in the math.h function library and two custom functions as parameters.

```//exercise14.11
#include <stdio.h>
#include <math.h>
#define LEN 10
void transform(double *source, double *target, int n, double (*p)(double));
double subtract(double x);//minus 1
void show(const double arr[], int n);
int main(void)
{
double source[LEN] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 ,8.0, 9.0, 10.0};
double target[LEN] = {0.0};
//double (*p)(double);

puts("source array:");
show(source, LEN);
puts("target array:");
show(target, LEN);

puts("implement add Target array after function:");
show(target, LEN);

puts("implement subtract Target array after function:");
transform(source, target, LEN, subtract);
show(target, LEN);

puts("implement sqrt Target array after function:");
transform(source, target, LEN, sqrt);
show(target, LEN);

puts("implement sin Target array after function:");
transform(source, target, LEN, sin);
show(target, LEN);

puts("The program ends.");
return 0;
}
{
return x + 1;
}
double subtract(double x)
{
return x - 1;
}
void show(const double arr[], int n)
{
int i;

for (i = 0; i < n; i++)
{
printf("%g ", arr[i]);
}
printf("\n");
}
void transform(double *source, double *target, int n, double (*p)(double))
{
int i;

for (i = 0; i < n; i++)
{
target[i] = p(source[i]);//Calling a function using a function pointer
}
}
```

Example output:

```source array:
1 2 3 4 5 6 7 8 9 10
target array:
0 0 0 0 0 0 0 0 0 0
implement add Target array after function:
2 3 4 5 6 7 8 9 10 11
implement subtract Target array after function:
0 1 2 3 4 5 6 7 8 9
implement sqrt Target array after function:
1 1.41421 1.73205 2 2.23607 2.44949 2.64575 2.82843 3 3.16228
implement sin Target array after function:
0.841471 0.909297 0.14112 -0.756802 -0.958924 -0.279415 0.656987 0.989358 0.412118 -0.544021
The program ends.
```

### 12. Question summary

#### 1. Input verification question

Generally, it is a menu selection, input the corresponding letter or number, and respond to the corresponding function. Here, the input can be regarded as a string, stored in a temporary array, and the input conditions must be met; for example, it is correct to only input a, a If there is a space or other characters in front, then the first element of this string array must be a and the second element must be a space; the option can be obtained using switch, and the corresponding input responds to the corresponding function.

#### 2. File problem

If a file needs to be read and written, if there is r+ mode, the fgetc() function can be used to judge the empty file. If it is an empty file, the corresponding data will be written into the file at the first run; after the data is obtained from the file , you can close the file first. If you want to write the changed data to the file, you can open the file in r mode, which will clear the file data and rewrite the desired data into the file.

#### 3. Pointer problem

The qualifier const is very important. There is no need to change the array or structure of the data content in the future. When used as a function parameter, the array can be represented by an array. When the structure is used as a function parameter, const should be added, so as not to change the content and the compiler will not remind.

Posted by jakobdoppler on Fri, 17 Mar 2023 21:21:03 +1030