Jin Anonuevo
Jin Anonuevo

Reputation: 95

Do while loop skipping in c

I'm still a beginner in c and I'm having trouble with this do-while loop here. It runs smoothly the first time but after i choose yes in try again. it skips the scanf for destination. it will only continue if i entered a number for the number of passengers.

#include <stdio.h>
#include <conio.h>
#include <windows.h>

char destination=' ';
int cash=' ';
int passenger=' ';
int multiply;
char again;
int change;
main(){
do{

printf("enter destination : \n");
printf("[Q] Quezon\n");
printf("[K] Kamuning\n");
printf("[A] Araneta Center Cubao\n");
printf("[G] Gilmore\n");
printf("[L] Legarda\n");
printf("[S] Santolan\n");

scanf("%c",&destination);
    int fare;

    switch(destination){
        case 'q':
        case 'Q':
            printf("Quezon city\n\n");
            fare = 11;

        break;
        case 'k':
        case 'K':
            printf("Kamuning\n\n");
            fare = 13;
        break;

        case 'a':
        case 'A':
            printf("Araneta Center Cubao\n\n");
            fare = 14;
        break;

        case 'G':
        case 'g':

            printf("Gilmore\n\n");
            fare = 16;
        break;

        case 'L':
        case 'l':

            printf("Legarda\n\n");
            fare = 20;
        break;

        case 's':
        case 'S':
            printf("Santolan\n\n");
            fare = 25;
        break;

    }



printf("Enter number of passenger\n");
scanf("%d",&passenger);

multiply = passenger*fare;

printf("\nTotal price: %d",multiply);

printf("\nEnter cash: ");
scanf("%d",&cash);
change=cash-multiply;

if(change<0){

printf ("\nchange: %d",change);
printf ("\nNot enough cash ");
}

else {
    printf ("\nchange: %d",change);
    printf ("\nSuccess");

}
printf("\n\n\nTry again? [y/n]: \n\n\n");
printf("---------------------------------------");
scanf("%s",&again);

}
while(again== 'Y' || again == 'y'|| change<0);
getch();

}

Upvotes: 1

Views: 343

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

It's because scanf() is a horrible function!

In this case, a '\n' was left in the input stream; when you execute scanf() again it consumes it and continues with the next one. You might be able to check that destination is indeed '\n' after the first iteration.

Note that scanf() is well designed; it's just not intuitive and that's why I say it's horrible, because it's incredibly difficult to use it correctly.

Most books teach taking input with scanf() and none of them explains how it works fully or how it should be used if you were to use it at all. Read this please scanf(3), but read it thoroughly. You will then notice that scanf("%d", &value) without checking what it returns, is simply wrong.

Upvotes: 1

Related Questions