Here is a program that prints a list of reminders for one month. This is an example of K.N. King of the book. My problem is that I cannot understand how the strcmp function works in this program.
#include <stdio.h>
#include <string.h>
#define MAX_REMIND 50
#define MSG_LEN 60
int read_line(char str[], int n);
int main(void) {
char reminders[MAX_REMIND][MSG_LEN+3];
char day_str[3], msg_str[MSG_LEN+1];
int day, i, j, num_remind = 0;
for(;;) {
if(num_remind == MAX_REMIND) {
printf("--No space left--\n");
break;
}
printf("Enter day and reminder: ");
scanf("%2d", &day);
if(day == 0)
break;
sprintf(day_str, "%2d", day);
read_line(msg_str, MSG_LEN);
for(i = 0; i < num_remind; i++)
if(strcmp(day_str, reminders[i]) < 0)
break;
for(j = num_remind; j > i; j--)
strcpy(reminders[j], reminders[j - 1]);
strcpy(reminders[i], day_str);
strcat(reminders[i], msg_str);
num_remind++;
}
printf("\nDay Reminder\n");
for(i = 0; i < num_remind; i++)
printf(" %s\n", reminders[i]);
return 0;
}
int read_line(char str[], int n) {
int ch, i = 0;
while((ch = getchar()) != '\n')
if (i < n)
str[i++] = ch;
str[i] = '\0';
return i;
}
I realized that the lines are stored in a 2D array in which each line receives a line from the user. The program first accepts the date (in two decimal words from the user) and converts it to a string using the sprintf () function. Then it compares the converted string date with the string stored in the reminder array [] [].
I can't figure out how it compares a date with a string. (It always returns true in this case and is interrupted for the operator at i = 0 each time).
source
share