Hello All...
The following is a variation on a program which maintains consistent string lengths before writing the array of structures to a text (or binary) file.
Following each user input, the remainder of the field is space-filled before writing the null terminator as the last character in the string.
Code:
#include<stdio.h>
#include<string.h>
#include<conio.h>
#define SPACES " "
#define MAX 3
struct student
{
char Id[6],address[30],telephone[7];
};
int main()
{
char input1[6], input2[30], input3[7];
int i, len;
struct student rec[MAX];
/* Enter details */
for(i=0;i<MAX;i++)
{
clrscr();
printf("ENTER STUDENT RECORD:\n\n");
printf("ID [ ]\n");
printf("ADDRESS [ ]\n");
printf("TELEPHONE [ ]");
fflush(stdin);
gotoxy(12,3);
fgets(input1,6,stdin);
len=strlen(input1);
strncat(input1,SPACES,(5-len));
input1[5]=NULL;
strcpy(rec[i].Id,input1);
fflush(stdin);
gotoxy(12,4);
fgets(input2,30,stdin);
len=strlen(input2);
strncat(input2,SPACES,(29-len));
input2[29]=NULL;
strcpy(rec[i].address,input2);
fflush(stdin);
gotoxy(12,5);
fgets(input3,7,stdin);
len=strlen(input3);
strncat(input3,SPACES,(6-len));
input3[6]=NULL;
strcpy(rec[i].telephone,input3);
} /* end for */
/* Display contents for space-filling to end of each field */
clrscr();
printf("ARRAY CONTENTS:\n\n");
for(i=0;i<MAX;i++)
printf("STUDENT %d\nId: %s\nAddress: %s\nTelephone: %s\n\n",
i+1, rec[i].Id, rec[i].address, rec[i].telephone);
printf("END OF RECORDS.");
return 0;
}
Does this help??
I am aware that fflush(stdin) has undefined behaviour. In this case, I found that omitting this line of code resulted in random jumps over the input fields... By including it, the program produced the desired results...
Salem has often commented:
> fflush (stdin);
This isn't standard - or more specifically, the effects are undefined.
This is better
while ( getchar() != '\n' ) continue;
Would he, or any board member, please suggest a line of code to suit my above program and eliminate the undesirable fflush()?
Look forward to your ideas. Regards from MrB