c - 在c中显示结构中的数字和字符串

标签 c

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

struct Directory {
    char Name;
    long int Number;
    int HouseNumber;
    char street;
};

int main(void)
{
    struct Directory contact;
    struct Directory *answer1, *answer2, *answer3, *answer4;
    char answer;

    printf("Welcome to Telephone Directory.\n\nPlease enter the name of the contact.\n");
    scanf("%s", &contact.Name);

    printf("Please enter the number of the contact.\n");
    scanf("%ld", &contact.Number);

    printf("Please enter the address of the contact.\n");
    scanf("%d %s", &contact.HouseNumber, &contact.street);

    answer1 = &contact;
    answer2 = &contact;
    answer3 = &contact;
    answer4 = &contact;

    printf("Would you like to obtain information on your contact? Enter 'yes' or 'no'.\n");
    scanf("%s", &answer);


    if (strcmp(&answer, "yes")==0) {
        printf("%s\n", &answer1->Name);
        printf("%ld\n", answer2->Number);
        printf("%d", answer3->HouseNumber);
        printf("%s", &answer4->street);
    }

    if (strcmp(&answer, "no")==0) {
        printf("Thank you for using Telephone Directory.\n");
    }

}

我正在尝试用 C 编写一个联系人程序。我希望该程序打印用户的家庭住址。我在结构中有“HouseNumber”变量,在结构中有“street”变量,将“answer3”设置为 int 变量以显示“HouseNumber”,将“answer4”设置为 char 变量以显示“street”。一起,我希望他们能在一个字符串中打印用户的地址,但是当我运行程序并在输入门牌号和街道后输入“yes”以显示联系信息时,程序崩溃,并显示 lldb 错误线程错误。似乎一切正常,因为我的编译器说代码没有问题,但它崩溃了。有人可以帮我解决这个问题吗?

最佳答案

当你执行 scanf("%s", &answer);

您正在将用户的输入写入 char answer; scanf 的参数需要有足够的空间来容纳整个字符串加上一个空字节。尝试类似的东西:

char answer[256];

这假设输入永远不会超过 256 个字符,但在像这样的简单程序中似乎是合理的。请注意,gcc 支持非标准的 %a,如果您传入 char*,它将为您分配一个字符串。

当您尝试存储字符串时,您需要确保有足够的空间容纳您放置的数据,就像在字典中只包含一个字符,否则您将溢出并占用您可能需要的其他内存稍后。

关于c - 在c中显示结构中的数字和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17659512/

相关文章:

c++ - 是否有任何操作系统允许将内存从一个地址移动到另一个地址而无需物理复制它?

C 代码删除文件中的 ^M/Windows 最后一个字符?

c - 在由 char 数组组成的数组中插入 char 数组元素

c - 使用 scanf 仅输入整数?

c - 调用结构体变量的区别

c - glibc:无效指针上的 fclose() 在 pthread_once() 中挂起

c - 什么客观情况会阻止将返回值也用作诊断?

c++ - 如何为 delete 编写一个 C 包装器,它可以快速释放任何给它的类型而不告诉它是什么类型

c - 我的 GCD 算法有什么问题?

c - fopen 不返回