Gyanendra
Gyanendra

Reputation: 35

Can scanf() function take single character value?

I was trying a simple C code and found out strange error. Here is the code. As soon as the first

scanf()

function is encountered, the compiler automatically skips it and move ahead. Why is that so?

#include<stdio.h>
#include<stdlib.h>
void main()
{
  float base_cost, refresh_cost;
int ticket;
char coupon, refresh, circle;
printf("Enter number of tickets: ");
scanf("%d", &ticket);
if(ticket<5 ||ticket>40)
{
    printf("Minimum of 5 and Maximum of 40 Tickets");
    exit(0);
}

printf("Do you want refreshment?(Y/N): ");     //Here compiler skips
scanf("%c", &refresh);
printf("Do you have coupon?(Y/N): ");
scanf("%c", &coupon);
printf("Enter circle: ");
scanf("%c", &circle);
if(circle!='k'||circle!='q' || circle!='K' || circle!='Q')
{
    printf("Invalid Input");
    exit(0);
}
else if(circle == 'k' || circle == 'K')
{
    if(ticket > 20)
        base_cost = (ticket*75.00) - 0.1*(ticket*75.00);
    else if(coupon == 'y' || coupon == 'Y')    
        base_cost = (ticket*75.00) - 0.02*(ticket*75.00);
    else
        base_cost = ticket*75.00;
}
else if (circle == 'q' || circle == 'Q')    
{
    if(ticket > 20)
        base_cost = (ticket*150.00) - 0.1*(ticket*150.00);
    else if(coupon == 'y' || coupon == 'Y')     
        base_cost = (ticket*150.00) - 0.02*(ticket*150.00);
    else
        base_cost = ticket*150.00;
}

if (refresh == 'y' || refresh == 'Y')   
{
    refresh_cost = ticket * 50.00;
}
else    
    refresh_cost = 0.00;

printf("\nTotal cost: %0.2f", base_cost + refresh_cost);

}

I used the variable refresh in order to allow the user to have a choice, whether or not to insert elements i.e. Y or N. Also, it looks like other scanf function with char as input are also been skipped. But the compiler basically skips the third scanf function, the one that accepts the char, along with the while loop.

Upvotes: 0

Views: 83

Answers (1)

John Bode
John Bode

Reputation: 123448

Unlike %d and %s, the %c conversion specifier does not skip over leading whitespace. What's happening is you have a stray newline in the input stream after the first scanf call to get the ticket number; that newline is read by the next scanf call and assigned to refresh.

To avoid this, put a blank space in front of the %c specifier:

scanf( " %c", &refresh );

That blank space tells scanf to skip over any leading whitespace. Do this for every %c that is meant to read a non-whitespace cparacter.

Upvotes: 2

Related Questions