0

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);
}
  • Welcome to SO. First of all, never ever use `gets`. It is considered dangerous (no possibility to check length of available buffer) and was removed from the C standard decades ago. – Gerhardh Sep 08 '22 at 12:35
  • 1
    You should not mix `(f)gets` and `scanf`. `scanf` ignores leading `\n` but `fgets` doesn't. Instead read your numbers using `fgets` into a buffer and then use `sscanf` to parse the numbers. BTW: Are you sure, a license number is really an integer? If they can have leading zeros or be alpha-numeric you should use a string instead. – Gerhardh Sep 08 '22 at 12:40

1 Answers1

-1

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.)

ryyker
  • 22,849
  • 3
  • 43
  • 87