2

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53

1 Answers1

1

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
}
anastaciu
  • 23,467
  • 7
  • 28
  • 53
  • Thank you, sir. After posting this question, i added fflush(stdin); after every scanf still it was not working. then i just added a space before the format specifiers and it worked. – the trickster Sep 24 '20 at 17:58
  • If you don't mind, sir, can you explain in brief about why that happens? I mean even after adding fflush? – the trickster Sep 24 '20 at 17:58
  • 2
    @thetrickster, fflush is meant to be used with stdout, using it with stdin may invoke undefined behavior, see https://stackoverflow.com/q/2979209/6865932. – anastaciu Sep 24 '20 at 18:08