0

每当我运行此代码时,获取“电子邮件”输入的最终 scanf 函数都不会执行,我会得到“更新成功!” 直接留言!我尝试使用gets()而不是 scanf 并且我遇到了同样的问题。有人可以向我解释这个问题吗?

输出图像

#include <stdio.h>
#include <stdlib.h>

typedef struct Directory
{
    char name[20], email[20];
    long int phone;
}Directory;

void add()
{
    Directory d;
    FILE *file;
    file = fopen("phonebook.bin", "ab");
    if(!file)
        printf("Failed to open file!");
    else
    {
        printf("Enter the name: ");
        scanf("%[^\n]", &d.name);
        printf("Enter the Phone Number: ");
        scanf("%ld", &d.phone);
        printf("Enter the e-mail ID: ");
        scanf("%[^\n]", &d.email);
        if(fwrite(&d, sizeof(Directory), 1, file))
            printf("Updated successfully!");
        else
            printf("Something went wrong, Please try again!");
    }
    fclose(file);
}

int main()
{
    add();
}
4

1 回答 1

1

您的代码中有多个问题。

  1. char 数组的正确格式是“%s”。我真的不知道什么是'%[^\n]'。

  2. 在 scanf() 中发送 char 数组的地址会导致内存损坏。数组的名称实际上是指向数组开头的 const 指针。例如: char a[10]; // a is somewhat equivalent to &a[0]. 在您的示例中,scanf() 的第二个参数需要一个地址,并且数组的名称已经是一个地址;数组第一个元素的地址。

您的代码应如下所示:

void add()
{
    Directory d;
    FILE* file;
    file = fopen("phonebook.bin", "ab");
    if (!file)
        printf("Failed to open file!");
    else
    {
        printf("Enter the name: ");
        scanf("%s", d.name);                   // ---> notice the %s format and the missing &
        printf("Enter the Phone Number: ");
        scanf("%ld", &d.phone);
        printf("Enter the e-mail ID: ");
        scanf("%s", d.email);                  // ---> same here 
        if (fwrite(&d, sizeof(Directory), 1, file))
            printf("Updated successfully!");
        else
            printf("Something went wrong, Please try again!");
    }
    fclose(file);
}

通过&d.email在 scanf 中执行操作,您将崩溃或获得未定义的行为。

发帖前请多做研究。

于 2020-04-09T14:54:18.233 回答