Vineeth Sai Vineeth Sai - 28 days ago 8
C Question

scanf input issue in this code

I am still a beginner in C. This code takes in input like

s 10
w 5
s 20
w 10


where s is travel time and w is wait time.

then it calculates total bill basing on traveltime and waittime and the fares which are declared as global variables.

This code is not accepting inputs in while loop properly. Can someone please tell me why is it happening like that. And if anything can be improved in this code is also much appreciated.

#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>


struct bill
{
int travelTime;
int waitTime;

float cost;

};

typedef struct bill BILL;

BILL *bill1;



int BASEFARE = 10; // in Rupees
int TRAVELFARE = 1; //in Rupees
float WAITFARE = 0.1; // in Rupees


int main()
{

int choice = 1;

bill1 = (BILL*)malloc(sizeof(BILL));

bill1->travelTime = 0;
bill1->waitTime = 0;

while(choice)
{
char state = ' ';
int period = 0;
printf("Enter state\n");
//scanf("%c %d",&state,&period);
scanf("%c %d",&state, &period);



if(state == 's')
{
bill1->travelTime = bill1->travelTime + period;
}
else if(state == 'w')
{
bill1->waitTime = bill1->waitTime + period;
}
else if(state == 'e')
{
printf("\nTotal TravelTime is %d s ",bill1->travelTime);
printf("\nTotal WaitTime is %d s", bill1->waitTime);

bill1->cost = BASEFARE + (bill1->travelTime * TRAVELFARE) + (bill1->waitTime * WAITFARE);

choice = 0;
}
else
{
printf("\nError in data format please ReEnter data\n");
free(bill1);
choice = 0;
}
}

printf("\nThe Final bill is %f", bill1->cost);

return 0;
}



OUTPUT
________________
Enter state
s 10
Enter state
w 5

Error in data format please ReEnter data

The Final bill is 0.000000


Answer Source

Change this:

scanf("%c %d", &state, &period);

to this:

scanf(" %c %d", &state, &period);

Whitespace in the format string matches 0 or more whitespace characters in the input.


PS: malloc() is declared in stdlib.h.

"malloc.h" is not a Standard header, so it shouldn't be like #include<malloc.h>. If it's a custom header, it should be enclosed with double quotes, like this: #include "malloc.h". If you don't have a custon header named "malloc.h", discard this include.


Unrelated to your problem, but Do I cast the result of malloc? No.