Could anyone advise why my scanf function only works once and it ends in a continuous loop.
#include <stdio.h>
#include <conio.h>
int main(void)
{
int accno;
float bbal, charge, rebate, limit, balance;
printf("Enter account number (-1 to end):");
scanf("%d", &accno);
while (accno != -1) // User input phase
{
printf("Enter beginning balance:"); // User input phase
scanf(" %.2f ", &bbal); // leave space after scanf("
printf("Enter total charges:");
scanf(" %.2f ", &charge);
printf("Enter total rebates:");
scanf(" %.2f ", &rebate);
printf("Enter credit limit:");
scanf(" %.2f ", &limit);
balance = bbal - charge + rebate;
// credit limit exceeded phase
if (balance > limit)
{
printf("Account: %u", accno);
printf("Credit limit: %.2f", limit);
balance = bbal - charge + rebate;
printf("Balance: %.2f", balance);
printf("Credit limit exceeded!");
}
printf("Enter account number (-1 to end):");
scanf("%d", &accno);
}
getch();
}
%.2fscanf()each time you call it to detect whether the conversion worked.if (scanf(" %.2f", &bbal) != 1) { …report error… }. Also, a trailing blank in a format string is a disaster in an interactivescanf(); the call won't terminate until you type the first character other than white space after the number — and that character will be left as the first character of the next input. If you type ahead the next number, you can move on — but the UI is not good.