为什么我的输入功能无法正确输入?

问题描述 投票:0回答:1

我是C的新手。我之前问过这个问题,我知道我的代码中有一个错误,但是仍然无法正常工作。我想从用户那里获取输入并将其存储在分配的内存中。 ptrsptr和Patientnum是全局变量。 ptrsptr指向另一个分配的内存,该内存存储了指向患者数据的指针。

  char name[51];
  int age=0;
  char agestr[3];
  char infectiondate [11];
  char address[51];
  char *patientptr;
  char **newptr;

  printf("\nEnter the patient name (50 characters at maximum): ");
  scanf ("%50s", name);

  newptr = (char**) realloc(ptrsptr, patientsnum*sizeof(char *));
  if (newptr) ptrsptr = newptr;
  else
  {
    patientsnum --;
    printf ("Not enough memory.\n");
    return;
  }

  patientptr = (char*) calloc (118, sizeof (char)); // allocation after being sure patient doesn't exist
  if (!patientptr)
  {
    patientsnum --;
    printf ("Not enough memory.\n");
    return;
  }

  strcpy(patientptr, name);

  printf("Enter the patient age: ");
  scanf ("%d", &age);
  sprintf (agestr, "%2d", age);
  strcpy((patientptr + 51),agestr);

  printf("Enter the patient date of infection (in form of dd/mm/year): ");
  scanf ("%10d", infectiondate);
  strcpy((patientptr + 54),infectiondate);

  printf("Enter the patient address (50 characters at maximum): ");
  scanf ("%50s", address);
  strcpy((patientptr + 65),address);

  *(ptrsptr+patientsnum-1) = patientptr;

  printf ("\nPatient added succesfully.\n");
}

输出为:

Enter the patient name (50 characters at maximum): John
Enter the patient age: 20
Enter the patient date of infection (in form of dd/mm/year): 20/10/2019
Enter the patient address (50 characters at maximum):
Patient added succesfully.

我无法输入地址。怎么了?

c string pointers dynamic-memory-allocation
1个回答
0
投票

[嗯,看来我还是一个对scanf不太了解的初学者。但是,看起来错误是将一些整数放入char字符串中。

© www.soinside.com 2019 - 2024. All rights reserved.