I've been testing this struct out and I get warning about using gets
. Somebody mentioned to use fgets
instead and replace the end with '\0'
. Any recommendation how I can change my code to do that?
void regCars(Car reg[], int *pNrOfCars) {
char again[WORDLENGTH] = "yes", model[WORDLENGTH], tmp[WORDLENGTH];
int year, milage;
while (strcmp(again, "yes") == 0) {
printf("Enter model:");
gets(model);
printf("Enter Year:");
gets(tmp);
year = atoi(tmp);
printf("Enter milage:");
gets(tmp);
milage = atoi(tmp);
reg[*pNrOfCars] = createCar(model, year, milage);
(*pNrOfCars)++;
printf("Continue? (yes/no)");
gets(again);
}
}
It's a little bit tricker than it looks. There's not much point just replacing gets with fgets(), if you then process a truncated line on over-long input and handle it as valid. You've merely replaced undefined behaviour with wrong behaviour.
if( fgets(line, sizeof(line), fp) )
{
if(!strchr(line, '\n'))
{
/* line is too long, what you do is up to you, but normally
we will discard it */
int ch;
while( (ch = fgetc(fp)) != EOF)
if(ch == '\n')
break;
}
else
{
/* line is a normal line with a trailing '\n' (gets trims the '\n') */
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With