Nathaniel Soh En Zhi
Nathaniel Soh En Zhi

Reputation: 19

C programming - While loop and scanf

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();
}

Upvotes: 2

Views: 447

Answers (2)

Panda
Panda

Reputation: 2520

In scanf("%.2f",&charge); their shouldn't be any space. Remove all the spacing.

Upvotes: 0

JeremyP
JeremyP

Reputation: 86691

When I try to compile the code in the question, I get a warning that the scanf format string %.2f is illegal. If I change it to %f (needed to remove the leading and trailing spaces too), it all starts working as expected. I'm using clang on a Mac, but it should be the same as Windows.

/Users/jeremyp/dev/foo/foo.m:19:18: warning: invalid conversion specifier '.' [-Wformat-invalid-specifier]
scanf(" %.2f ", &charge);
       ~~^

Anyway, as one of the comments states, currency is not a floating point number. There are many ways to store currency, possibly the best is a large integer type e.g. a 64 bit int will do but storing the currency in cents or pence or whatever the lowest denominational unit is in your currency of choice.

Upvotes: 3

Related Questions