Your gets
call is unsafe. It can accept more characters than you have allocated. Boom.
Assuming you have allocated at least 8 bytes for .idCard
(i.e. 7 chars plus terminator) then consider using this:
fgets(newRes.idCard, 7+1, stdin);
This ensures you will not accept too many chars. It will truncate as necessary. Check the return value of fgets
for success.
(man fgets
)
Compile this example code and study. I hope you find what you're looking for in here.
#include <stdio.h>
#include <string.h>
#define MAX_ID_LEN (7)
int main() {
char idCard[MAX_ID_LEN+1];
printf("ID: ");
if (fgets(idCard, MAX_ID_LEN+1, stdin)) {
char *cLast = idCard + strlen(idCard)-1;
if (*cLast == '\n')
*cLast = 0; // strip newline *if* present
printf("Success! idCard='%s'\n", idCard);
} else {
printf("Failure.\n");
}
return 0;
}
Note there are several lines of code there to check if the input includes a newline char and remove it. fgets
ensures a newline unless the user entered more than 7 characters for the ID. I hope this is clear for you.
Alternatively, this is probably less distracting for you: (just use fscanf
)
#include <stdio.h>
int main() {
char idCard[7+1];
printf("ID: ");
fscanf(stdin, "%7s", idCard);
printf("idCard='%s'\n", idCard);
return 0;
}