Multiple scanf() are used for getting string and an integer. Some of them are getting ignored

Viewed 57

Here is the code :

#include<stdio.h>
#include<stdlib.h>
typedef struct _car {
    char *engine;
    char *model;
    int mileage;
} car;


car car1;
int main()
{
    car car2;
    car1.engine = (char *)malloc(100*sizeof(char));
    car2.engine = (char *)malloc(100*sizeof(char));
    car1.model = (char *)malloc(100*sizeof(char));
    car2.model = (char *)malloc(100*sizeof(char));
    printf("\nEnter the Engine, model and mileage of the car1 :");
    scanf("%[^\n]s",car1.engine);
    scanf("%[^\n]s",car1.model);
    scanf("%d",&car1.mileage);
    printf("\nEnter the Engine, model and mileage of the car2 :");
    
    scanf("%[^\n]s",car2.engine);
    scanf("%[^\n]s",car2.model);
    scanf("%d",&car2.mileage);
    printf("\nEngine = %s , Model = %s and mileage = %d" , car1.engine , car1.model , car1.mileage);
    printf("\nEngine = %s , Model = %s and mileage = %d" , car2.engine , car2.model , car2.mileage);

    return 0;
}

And here is the output :

Engine =  engine 1 , Model =  and mileage = 0                                        
Engine = model 1 , Model =  and mileage = -1307142624                                    

...Program finished with exit code 0  

So I entered 'engine 1' then 'model 1' then it asked for car2 info instead of letting me enter mileage, so I entered 'engine 2'.

It skipped the input for car1.model , car1.mileage and car2.model.

1 Answers

Use:

//...
printf("\nEnter the Engine, model and mileage of the car1 :");
scanf(" %99[^\n]",car1.engine); //s is not used in this specifier
scanf(" %99[^\n]",car1.model);
scanf("%d",&car1.mileage);
printf("\nEnter the Engine, model and mileage of the car2 :");
    
scanf(" %99[^\n]",car2.engine);
scanf(" %99[^\n]",car2.model);
scanf("%d",&car2.mileage);
//...

The space before the specifier discards the newline character that remains in stdin after the input.

It's also advised to use a size limit when reading strings to avoid buffer overflow, as your buffers have space for 100 characters, 99 is the size you should use, leaving the last character for the string null terminator.

Just to be thorough, you should check scanf return to make sure the input was read properly, e.g:

if(scanf(" %99[^\n]",car1.model) == 1){ 
    //Ok, 1 value read
}
else{
    //handle bad input situation
}
Related