-
Enter data in struct
This function should accept student details from the user and store them in a structure. I'm using a temp array to hold the reg number as I'm going to perform a validation test on it later.
Code:
void add_student(studentRecord student[],int i){
system("cls");
printf("\nEnter Registration number :");
gets(temp);
strcpy(student[i].regNumber,temp);
printf("\nEnter Surname :");
gets(student[i].surname);
printf("\nEnter Forename :");
gets(student[i].forename);
printf("\nEnter number of credits :");
scanf("%d",&student[i].credits);
printf("Press any key to continue.\n");
}
When I display the structure I have some strange output i.e.
*** Input***
reg No : 1234
Surname : smith
Forename: john
Credits : 12
*** Actual output ***
reg No: 1234smith
Surname: smith
forename: john
credits: 6684136
Can any one help? I cant see why the Surname is being appended onto the Reg No or why the Credits are being displayed as an address ( I think ??!!)
if its any help this is the function I'm using to display the structure, for testing:
Code:
void display(studentRecord student[],int i){
printf("\nReg %s\n",student[i].regNumber);
printf("\nsurname %s\n",student[i].surname);
printf("\nforename %s\n",student[i].forename);
printf("\ncredit %d\n",student[i].credits);
getch();
}
-
You're inputting the information backwards, it would be best to use strcpy() for copying the names in, and just fgets() with an atoi() or atof() function to convert. Then just assign those values returned to the structure members. Think strcpy() for strings and fgets() (atoi/atof) for integer/float values.
-
As to your first error: How many bytes is regNumber? I would wager it's only 4 bytes -- but "1234" takes up *five* bytes because it has to be null terminated. If it has to be a pure number you're better off using an integer and atoi() to get the number.
Show us how the struct itself is defined.
-
thanks for taking a look at this guys...
I tried the strcpy() but still get the same result.
here is the struct :
Code:
typedef struct {
char regNumber[4];
char surname[20];
char forename[15];
int credits;
}studentRecord;
I fixed the second problem (displaying the int credits) but still cant get the regNumber / surname problem fixed.
the regNumber has to be alphanumeric as it may contain a letter.
-
The answer is as described. Your first array is not long enough to store the null terminator. As such, when displaying a string, it just runs along merrily until it encounters an actual null.
Try using strncpy instead, and specify "array size - 1" for the third argument.
Quzah
-
AAAhhhhhh! :D
working fine now. thanks very much guys, much appreciated.