'enter' from previous input is stored in string

Viewed 37

The programme does not ask for name of driver 2 and driver 3 and skips to the license no. I guess this is because the 'enter' from previous input is stored in string

void func1(char name[], int *lic, int *km)
{
printf("Enter your name:-\n");
gets(name);

printf("Enter your license no.:-\n");
scanf("%d", lic);

printf("Enter number of kilometers driven:-\n");
scanf("%d", km);
}
1 Answers

The newline from a buffer read from stdin, using fgets() or scanf() can be removed before subsequent calls. Example with fgets():

fgets(name, sizeof name, stdin);
name[strcspn(name, "\n")] = 0;

The prototype though should include the size of the buffers, and accommodate space for drivers names. Example handles two names:

void func1(int num, int size, char name[num][size], int *lic, int *km)
{
    printf("Enter name 1:-\n");
    fgets(name[0], size, stdin);
    name[0][strcspn(name[0], "\n")] = 0;

    printf("Enter name 2:-\n");
    fgets(name[1], size, stdin);
    name[1][strcspn(name[1], "\n")] = 0;

    printf("Enter driver's license no of driver.:-\n");
    scanf("%d", lic);

    printf("Enter number of kilometers driven:-\n");
    scanf("%d", km);
}

Then in main()

char names[2][30] = {0};
int lic = 0, b = 0;
func1(2, 30, names, &lic, &km);  

(Note that using gets() is problematic.)

Related