Search code examples
cstringpointersdynamic-memory-allocation

Why does my input function doesn't get input correctly?


I'm new to C. I asked this question before, I knew an error in my code, but still, it is not working. I want to take input from the user and store it in allocated memory. ptrsptr and patientsnum are global variables. ptrsptr points to another allocated memory that stores pointers to patients' data.

  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");
}

The output is:

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.

I can't input the address. What is wrong?


Solution

  • Well, it looks I am still a beginner that doesn't know much about scanf. But, it looks the error was putting some integer into char string.