C程序从用户那里获取联系并将其添加到文件中

标签 c printf scanf

我编写这段代码是为了获取用户的输入并将其添加到文件中。当我在在线编译器上运行这段代码时,我收到一条消息,通知我调用 scanf 函数时出现问题。我无法理解这个问题。你能帮我解决这个问题吗?

#include <stdio.h>
typedef struct {
    char firstName   [20];
    char lastName    [20];
    int  phoneNumber [10];
    char email       [50];
    char address     [100];
    int  dayOfBirth  [2];
    int  monthOfBirth[2];
    int  yearOfBirth [4];
} contact;

void addcontact() {
    FILE *p,*q;
    p = fopen("p.txt", "r+");
    printf(" please enter the first name");
    scanf(" %s", &contact.firstName);
    printf(" next, enter the last name");
    scanf(" %s", &contact.lastName);
    printf(" enter the phone number");
    scanf(" %d", &contact.phoneNumber);
    printf(" enter the email");
    scanf(" %s", &contact.email);
    printf(" enter the address");
    scanf(" %s", &contact.address);
    printf(" enter the day , month and year of birth");
    scanf(" %d %d %d", &contact.dayOfBirth, &contact.monthOfBirth, &contact.yearOfBirth);
    q = fclose(p);
}

我什至试图删除 &

PS:该项目是一个电话簿。

最佳答案

您试图在未声明结构变量的情况下读取输入。

typedef struct{
  char firstName [20];
  char lastName[20];
  int phoneNumber[10];
  char email[50];
  char address[100];
  int dayOfBirth[2];
  int monthOfBirth[2];
  int yearOfBirth [4];
}contact;

scanf(" %s",&contact.firstName);

contact 是数据类型。 您需要声明 contact 类型的变量。

示例:

contact input;
scanf(" %s", input.firstName);

关于C程序从用户那里获取联系并将其添加到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53930965/

相关文章:

c - valgrind 在打印分配的字符串时报错

c - 如何阻止程序将多个字符存储到 char 变量中?

c - 如何在C中对单个字符执行scanf

c - 如何读取文件行(整​​数)并对从 A 行到 B 行的总数求和?

c - 为什么 Windows 返回代码称为 HRESULT?

c - 从编译器之间的 printf() 获得一致的输出

c - 我怎样才能在 ansi C90 中捕获运行时错误

c - 执行带有参数的 SQLite 语句

c - 晶体管的C/数学模型

c++ - Arduino液晶显示屏: Generate a navigation menu by reading an array