-
infinite loop kicks in
I can't see what's wrong here, any idea why when I enter q ( which should jump out of the loop ) does the program begin an infinite loop:
Code:
do {
title (); // a self-defined function for printing text
printf("\nPlease enter the cost of the item(s)\n");
printf("(Press q to finish)\n:");
scanf("%f",&price);
clrscr();
cost += price;
}
while ( price != 'q' );
-
You can't store letters in a float variable.
-
You are scanning a float and then testing it for a character value? That just won't work.
You will have to either:
-scan a 'q' and test it for the value that scanf returns when expecting a float, and then use this value in place of the current 'while' condition,
-use fgets, and test it for q, then transform it with a call to atof, (which is probably better, anyway).
And actually, since in this case, we know noone will enter '0' for a price, we can exploit the fact that atof returns 0 if a char-containing string is passed into it.
Like this:
if( (price = atof( fgets(chPrice, 15, stdin)) == 0 )
break;
cost += price;
-
>if( (price = atof( fgets(chPrice, 15, stdin)) == 0 )
Be careful doing this, if fgets() returns NULL, then your program will crash.
-
Well, with file streams, this will probably happen, and often ;) But with keyboard input, I have never had such a problem, EVER. You will always get *at least* a newline. But good eye :D
-
I agree Seb, but I never trust a user to do the right thing! They can hit CTRL+D or CTRL+Z on a blank line and it will force a NULL from fgets().
-
Really? Well, in that case, the bottom line is: "Always perform a sanity check on your fgets() ret val"!!! :D Thanks for the tip, Hammer.