【问题标题】:Semantic error in structures结构中的语义错误
【发布时间】:2015-08-12 17:30:08
【问题描述】:

代码的目的是存储借书证信息并使用作者的姓氏搜索书籍。当我使用作者姓名搜索时,它显示“未找到此作者姓氏的书籍”。下面是我的代码。我在这里做错了什么?

//Program to store Library card Information and search for record using last name
#include<stdio.h>

void search(struct lib_card *name)

struct author
{
    char fname[20];
    char lname[20];
};

struct pub_date
{
    int day;
    int month;
    int year;
};

struct lib_card //Structure declaration for storing Library card information
{
    char title[80];
    struct author name;
    struct pub_date date;
};

void main()
{
    struct lib_card card[2];
    int l; //l is a variable assigned for loop
    for (l = 0; l < 2; l++)
    {
        printf("********Enter Library Card Information********\n");
        printf("Card # %d\n", l + 1);
        printf("Enter Book Title:             ");
        scanf("\n%[^\n]s", card[l].title);

        printf("Enter Author's First name:  ");
        scanf("\n%s", card[l].name.fname);

        printf("Enter Author's Last name:   ");
        scanf("\n%[^\n]s", card[l].name.lname);

        printf("\nEnter Published date:\n");
        printf("\t\tdate(dd):");
        scanf("\n%d", &card[l].date.day);

        printf("\t\tMonth(mm):");
        scanf("\n%d", &card[l].date.month);

        printf("\t\t\Year(yy):");
        scanf("\n%d", &card[l].date.year);
    }

    search(card); //Structure's address is passed to search function
}

void search(struct lib_card *name)
{
    char llastname[20];
    int l;

    printf("\nEnter Author's Last name to search for books:");
    scanf("\n%[^\n]s", llastname); //Get author's last name to search the books

    for (l = 0; l < 2; l++)
    {
        printf("%s\n", (name + l)->name.lname);
        if ((name + l)->name.lname == llastname)
        {
            printf("%s\n", (name + l)->title);
        }
        else if (l == 1)
        {
            printf("\nNo books by this Author's Last name found");
        }
    }
}

【问题讨论】:

  • 请提供您在编译或运行代码时遇到的错误。
  • 您是否尝试过使用调试器或一些调试打印来查找错误?
  • 1) 修正你的代码格式,这样就可以在不把大脑变成椒盐卷饼的情况下实际阅读它,2) 使用 strcmp() 或类似的东西来比较以 NULL 结尾的 C 字符串,而不是 ==
  • 我开始编辑你的代码,但我没有时间。首先,它需要格式化为代码:突出显示代码并单击{} 图标(这会将其缩进 4 列)。使用一致的缩进,不要加倍空格;空行有利于显示整体结构,但您不需要在每一行代码之后都留一个空行。 void main() 应该是 int main(void)。而且您需要一个标签来指定您使用的语言(我会添加)。

标签: c string pointers if-statement structure


【解决方案1】:

这不是比较字符串的正确方法:

if ((name + l)->name.lname == llastname)

改用strcmp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 2016-08-18
    • 1970-01-01
    相关资源
    最近更新 更多