-1

I'm trying to figure out how I can assign different inputs to different structure variables. For example, if one user inputs his/her name then it gets assigned to p1.name, and if the next person inputs his/her name it gets assigned to p2.name and so on.

struct patient {
    int number;
    char name;
    char status;
    char medications;
    float bill;
};

struct patient p1, p2, p3;
printf("Name: ");
scanf("%c", &pname);
skratpa
  • 130
  • 12
Leila K.
  • 77
  • 6

2 Answers2

1

To store names, you should use char arrays (strings):

struct patient {
    char name[51];
    // ...
};

To get patients in a row, use a loop:

#define NUMBER_OF_PATIENTS  10
// ...
struct patient patients[NUMBER_OF_PATIENTS];
// ...
for(int i = 0; i < NUMBER_OF_PATIENTS; i++) {
    printf("Name: ");
    fgets(patients[i].name, 50, stdin);
    // ...
}

Also, scanf("%c", &ch) reads a single character, not a string. You should look up C strings here.

Enzo Ferber
  • 3,029
  • 1
  • 14
  • 24
0

For numeric types, you'd use the & operator with the structure name and the . member selection operator:

scanf( "%d", &p1.number );
scanf( "%f", &p1.bill );

For strings, you first need to declare each member as an array of char:

#define MAX_NAME_LEN 40
#define MAX_STATUS_LEN 20
#define MAX_MEDICATION_LEN 100

struct patient
{
  ...
  char name[MAX_NAME_LEN+1]; // plus 1 for string terminator
  char status[MAX_STATUS_LEN+1];
  char medications[MAX_MEDICATION_LEN+1];
  ...
};

then you should read each string using fgets:

if ( !fgets( p1.name, sizeof p1.name, stdin ) )
  // error on read

You could use scanf to read string inputs, but it requires some work to make it secure. It's just easier and safer to use fgets.

One quirk of fgets is that it stores the trailing newline to the buffer if there's room, so you will want to add a couple of checks for it. If it is present, you probably want to remove it so it doesn't cause problems. If it isn't present, then you probably want to consume any remaining input in the input stream so it doesn't foul up the next read:

char *newline = strchr( p1.name, '\n' );
if ( newline )
  *newline = 0;
else
  while ( getchar() != '\n' )
    ; // empty loop body
John Bode
  • 119,563
  • 19
  • 122
  • 198