c - 一月提醒程序中的strcmp()函数理解

标签 c arrays

这是打印一个月提醒列表的程序。这是 K.N. 的一个例子。王书。我的问题是我不明白 strcmp 函数在这个程序中是如何工作的。

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

#define MAX_REMIND 50       /* Maximum number of reminders */
#define MSG_LEN 60          /* max length of reminders message */

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;
}

我的理解是,字符串存储在二维数组中,其中每一行都接受来自用户的字符串。该程序首先获取日期(来自用户的两位小数)并使用 sprintf() 函数将其转换为字符串。然后它将转换后的字符串日期与存储在 reminder[][] 数组中的字符串进行比较。

我不明白它是如何比较日期和字符串的。 (在这种情况下它总是返回 true 并且每次都在 i = 0 处中断语句)。

最佳答案

此代码中使用的

strcmp 用于排序。添加一些调试代码(在第 27 行之后),您将看到 strcmp 产生的结果:

for(i = 0; i < num_remind; i++) {
    printf("%s comparing to %s is %d \n", day_str, reminders[i], strcmp(day_str, reminders[i]));
    if(strcmp(day_str, reminders[i]) < 0) {
            break;
    }
}

如您所见,当新输入的 day_str 小于存储提醒开头的任何其他提醒时,for 循环被中断。 以这种方式获得的i用于下一个for循环,将所有存储的提醒从num_remind转移到i按 1 位(从最后一个元素到 i)。 最后这两行将 day_str 和 msg_str 放在正确的位置:

strcpy(reminders[i], day_str);
strcat(reminders[i], msg_str);

看看这个Insertion sort理解这种排序。

关于c - 一月提醒程序中的strcmp()函数理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15314072/

相关文章:

c - 如何清除 C 中的 unsigned char 数组位?

编译器错误 : "Expected ;" error in C struct

arrays - 如何使用where子句检查postgres数组中是否存在值

java - 向右移动数组 - 作业

c - (新手) strstr() 返回带有无符号参数的 null

c++ - 套接字上的并行读/写

c - 如何嵌入内联汇编来调用 sys_unlink?

c++ - 验证C中数组的大小

arrays - 如何修改具有给定索引的数组值?

java - 如何循环遍历数组来查找参数是否与数组中的元素匹配?