Home > Software design >  Code skips the input for the name of driver 2 & 3 but prints for driver 1 as well prints the output
Code skips the input for the name of driver 2 & 3 but prints for driver 1 as well prints the output

Time:12-02

I was writing code to prints the details of three drivers but the problem is the program takes the input of driver 1 correctly but skips the input for name for driver 2 and 3 ,also despite providing the input it prints the distance travelled as 0.0.

#include<stdio.h>
struct data
{
    char name;
    int dlo;
    char route;
    float km;
}s1,s2,s3;
void details(struct data *d)
{
    printf("Enter your name: ");
    scanf(" %s",&d->name);
    printf("Enter your driving license no: ");
    scanf("%d",&d->dlo);
    printf("Enter route taken: ");
    scanf("%s",&d->route);
    printf("Enter distance travelled: \n");
    scanf("%.2f",&d->km);
}
void output(struct data *d)
{
    printf("Driver name: %s\n", &d->name);
    printf("Driving license no: %d \n", d->dlo);
    printf("Route taken: %s\n", &d->route);
    printf("Distance travelled: %.2f \n", d->km);
}
int main()
{
        printf("\n--------------driver 1---------------\n");
        details(&s1);
        printf("\n");
        output(&s1);
        printf("\n--------------driver 2---------------\n");
        details(&s2);
        printf("\n");
        output(&s2);
        printf("\n--------------driver 3---------------\n");
        details(&s3);
        printf("\n");
        output(&s3);
    return 0;
}

the output comes likes this:

--------------driver 1---------------
Enter your name: abhishek
Enter your driving licence no: 123
Enter route taken: abcd
Enter distance travelled: 
123

Driver name: abhishek
Driving licence no: 123
Route taken: abcd
Distance travelled: 0.00

--------------driver 2---------------
Enter your name: Enter your driving licence no: 321
Enter route taken: efgh
Enter distance travelled: 
45 

Driver name: 123
Driving licence no: 321
Route taken: efgh
Distance travelled: 0.00

CodePudding user response:

The problem was that I used %.2f in the scanf which resulted in a Run-Time Error thus by changing the scanf("%.2f",&d->km); to scanf("%f",&d->km); the error was solved also I had to use array for name and route to avoid further Run-Time Error.

I really appreciate everyone for their advice.

  • Related