Unhandled exception in my modified code - c

I am writing a POS system for HW, and I had to take my first code which used hundreds of variables and change it into a more compact program using arrays. This is my new code:
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------
//------------------------------------------Declaring-Variables--------------------------------------------
//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------
//Discount Variables
int iPerPurchaseDiscountPercent = 0; //enter a number which will be later changed to a percentage
int iFinalPurchaseDiscountPercent = 0;//enter a number which will be later changed to a percentage
float fPerPurchaseDiscountPercent = 0;//the percentage value of discount per item
float fFinalPurchaseDiscountPercent = 0;//percentage value of final dicount
float fPerPurchaseDiscountPrice = 0;//price at which discounts will be applied
float fFinalPurchaseDiscountPrice = 0;//price at which the final shop discount will be appled
//Array values for math
float fItemPrice[100] = { 0 }; //Price of Item
int iItemQuantity[100] = { 0 }; //Quantity of that Item
float fBundleCost[100] = { 0 }; //Price before Discounts (fItemPrice[N] * fItemQuantity[N])
float fDiscountPerItem[100] = { 0 }; //What discount is recieved per item (fItemPrice[N] * iPerPurchaseAmount)
float fItemTotalDiscountRecieved[100] = { 0 }; //Total discount recieved on multiple items of same type (fDicountPerItem * iItemQuantity)
float fDiscountPrice[100] = { 0 };//Price for item after all discounts (fBundleCost - fDiscountRecieved)
//Values for while loop
bool bStillShopping = true;
int iItemCount = 0;
char cExitQuestion = 'y';
//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------
//-----------------------------------------------Prototyping-----------------------------------------------
//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------
//------------------------------------------------Main-Loop------------------------------------------------
//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------
int main(void)
{
printf("Welcome to Blacketts bookstore!\t\t\t\t\t\tPOS V2\n");
//Taking values for the per item discounts
printf("Please enter the price that discounts per item will be applied: ");
flushall();
scanf("%f", &fPerPurchaseDiscountPrice); //takes the value at which items will be discounted
printf("Please enter the percentage to be applied at this price: ");
flushall();
scanf("%d", &iPerPurchaseDiscountPercent); //takes a value eg 10 to be later changed to .1 for 10%
fPerPurchaseDiscountPercent = iPerPurchaseDiscountPercent/100; //changes the int to a float and makes it appropriate for percentage calculations
//Taking values for the final purchase discount
printf("Please enter the price that end of sale discounts will be applied to: ");
flushall();
scanf("%f", &fFinalPurchaseDiscountPrice); //takes the value at which the whole docket will be discounted by
printf("Please enter the percentage to be applied at this price: ");
flushall();
scanf("%d", &iFinalPurchaseDiscountPercent);//takes a value eg 5 to be later changed to .05 for 5%
fFinalPurchaseDiscountPercent = iFinalPurchaseDiscountPercent/100; //changes the int to a float and make it appropriate for percentage calculations
//While loop to take values and input them into appropriate places
while(bStillShopping == true)
{
iItemCount = 1; // Counting how many items are being purchased, 0 = 1st item. therefore Total quantity Items must equal iItemCount+1
printf("\nPlease enter the price of the first item to be purchased: "); //enter price of item
flushall();
scanf("%.2f", fItemPrice[iItemCount]);
printf("Please enter the quantity of that item: "); //enter quantity
flushall();
scanf("%d", iItemQuantity[iItemCount]);
printf("\nWould you like to enter any more Items? (y/n): "); //ask to continue
flushall();
scanf("%c", &cExitQuestion);
if(cExitQuestion == 'n')
{
bStillShopping = false; //if dont want to continue exit the loop
}
else
{
iItemCount++; //if do continue increment item loop and ask for more variables
}
}
getch();
}
When I get to inputting the quantity at iItemQuantity[iItemAmout] it will crash the program with an unhandled exception. I also did some debugging print statements inbetween code to see where it gets to and output what variables I inputed and the returned values did not match up, all I received were 0.00.
Help would be much appreciated and I hope I am not asking an already answered question somewhere else. Still don't really know how to navigate the site.
I know the code does not do anything else at present time but I do not see the point in continuing until the first problems are corrected.

use & in scanf for array elements also
like this
scanf("%.2f", &fItemPrice[iItemCount]);
scanf("%d", &iItemQuantity[iItemCount]);

The problem is that scanf expects pointers to the values, not the actual values themselves. You do it correctly before the loop, but not for the input inside the loop.
Change e.g.
scanf("%.2f", fItemPrice[iItemCount]);
to
scanf("%.2f", &fItemPrice[iItemCount]);
or
scanf("%.2f", fItemPrice + iItemCount);
Do the same for all input.

Related

Variable changes midway through loop and I can't figure out what's the problem

I'm writing some code to calculate GPA and when I start a loop, one of my variables "numClasses" changes value to a huge number midway through the loop and I can't figure out what's going on.
#include <stdio.h>
int main()
{
float crdtHrs[] = {}; //Credit hours for this term
float numClasses; //Amount of classes taken this term
float qltyPoints[] = {}; //Quality points for term
float classes[] = {}; //Array for class grades
printf("Please enter total number of classes -> ");
scanf("%f", &numClasses);
float a = numClasses; //using new variable because this way the loop works
for(int i = 1; i <= a; i++)
{
printf("\nGPA class #%d -> ", i);
scanf("%f", &classes[i - 1]);
printf("Credit hours for course -> ");
scanf("%f", &crdtHrs[i - 1]);
printf("%f", numClasses); //at some point of my loop numClasses changes value
}
return(0);
}
Nice zero length array buffer overrun. Boom. Let's arrange so the arrays are declared a little later so we can give them sizes.
printf("Please enter total number of classes -> ");
scanf("%f", &numClasses);
int a = (int)numClasses;
float crdtHrs[a]; //Credit hours for this term
float qltyPoints[a]; //Quality points for term
float classes[a]; //Array for class grades
Now we allocate the arrays on the stack at the right size.

How to fix segmentation fault for while loop in c

I'm working on an assignment and trying to write the code to answer this question:
Write a program that computes the total weight of a cargo. The user has many types of boxes (numbered 1 to n). For each box type, the program asks the user about the weight and quantity. The program thencomputes and prints the total cargo weight.
In the output sample below, the user has three box types. For box type 2, the user enters the sentinel -1 to
indicate they’re done with the input. Your program should print Type 1, 2, 3, etc. as shown in the
output below.
Enter weight (lbs) of Type 1 box: 4
Enter quantity: 2
Enter weight (lbs) of Type 2 box: -1
The total weight is 8 lbs.
When i run this code it runs the first line to input weight but then gives me a segmentation fault and says (core dumped). -1 is the sentinel and even when the enter weight is inside the while loop the result is the same. What am I doing wrong? I'm sorry I'm new to C
#include <stdio.h>
int main()
{
int weight; //weight of boxes
int quantity; //number of boxes
int total_weight; //total weight
int n = 1;
printf("Enter weight (lbs) of Type %d box: ", n);
scanf("%d", weight);
while(weight!=-1) //Iterate loop until w=-1
{
printf("Enter quantity: \n");
scanf("%d", quantity);
total_weight= total_weight + (quantity*weight);
n++;
}
printf("The total weight is %0.2d", total_weight);
return 0;
}
This is not how you use scanf
scanf("%d", weight);
scanf("%d", quantity);
You should pass the address of the variable, not the value of the variable.
That would look like this:
scanf("%d", &weight);
scanf("%d", &quantity);
Your while loop depends on value weight. The value of weight never changes in your loop, so the loop can never exit.
This line:
total_weight= total_weight + (quantity*weight);
uses the value of total_weight, which was never initialized.
You should initialize your variables.
All in all, I think your fixed code should look like:
#include <stdio.h>
int main()
{
int weight = 0; //weight of boxes
int quantity = 0; //number of boxes
int total_weight = 0; //total weight
int n = 1;
while(weight!=-1)
{
printf("Enter weight (lbs) of Type %d box: ", n);
scanf("%d", &weight); // Update weight **inside** the loop
printf("Enter quantity: \n");
scanf("%d", &quantity);
total_weight= total_weight + (quantity*weight);
n++;
}
printf("The total weight is %0.2d", total_weight);
return 0;
}
while(weight!=-1) //Iterate loop until w=-1
{
printf("Enter quantity: \n");
scanf("%d", quantity);
total_weight= total_weight + (quantity*weight);
n++;
}
Problem is in while condition, weight never change it's value so the condition always true so infinite loop.
Fix this statement scanf("%d", &weight);
Your problem is you are trying to assign a value to the pointer of quantity and weight, instead you need to put &quantity and &weight also you do not have another input for the weight, you should also use a do while instead of a while loop. It should look like this
#include <stdio.h>
int main()
{
int weight; //weight of boxes
int quantity; //number of boxes
int total_weight; //total weight
int n = 1;
do
{
printf("Enter weight (lbs) of Type %d box: ", n);
scanf("%d", &weight);
printf("Enter quantity: \n");
scanf("%d", &quantity);
total_weight= total_weight + (quantity*weight);
n++;
}while (weight != -1);
printf("The total weight is %0.2d", total_weight);
return 0;
}

Incorrect output for a particular code. (Maximum, minimum, grade_scanner)

I've been trying to figure this out the last few days, but no luck. The objective is to find the sum, average, minimum, and maximum grades and display them.
Here is my code, everything except minimum, maximum and grade input seem to work
// Includes printf and scanf functions
#include <stdio.h>
int main(void) {
unsigned int counter; // number of grade to be entered next
int grade; // grade value
int total; // sum of grades entered by user
float average; // average of grades
int maxi; // Max grade
int mini; // min grade
int i;
int max;
int min;
maxi = 1;
mini = 1;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
//scanf("%d%d", &min, &max);
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
//scanf("%d",&counter);
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
break;
}
else {
total = total + grade;
average = (float)total / counter; // NOTE: integer division, not decimal
}
}
max = (grade < maxi) ? maxi : grade;
min = (grade > mini) ? mini : grade;
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
Output:
Enter number of grades: 2
5
7
Enter grade 1: 4
Enter grade 2: 3
Class average is: 3.500
Your maximum grade is 3
Your minimum grade is 1
Sum: 7
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade" then from there it calculates everything. Also, it seems that the Maximum is always the last grade that I enter and shows 1 as the minimum when no where in the input is 1. I am supposed to use a conditional operator for the max/min, I tried looking it up and reading the book, but they just use letters like a,b,c, etc. Which just confused me so I'm not sure if I did it wrong.
Could that be what is messing everything up? If it isn't what am I doing wrong?
Another thing is I'm thinking I need a While loop if I want to make the counter have an input from 1-100, is that right?
Edit: just realized I had to remove the scanf for max and min. Taht's why I had to inptu 2 nubmers first
There are two major problems, as I see it
The variable total is not initialized, so the first occurrence of total = total + grade; would invoke undefined behaviour.
You have to initialize it explicitly to 0.
The same variable grade is used for holding the repeated input. After the loop, grade will only hold the last input value.
You need to either use an array for storing inputs and comparison, or, compare and update the min and max as you go, inside the loop.
For future references, please seperate your code in different functions or add comments, since analyzing an unfamiliar code always takes much time.
min: Your problem here lies, that you're initializing your min value with 1. That value is most of the time below your input grades. If you want to initialize it, you should use a high number.
For example:
#include <limits.h>
int min = INT_MAX;
max: Your "grade" will be always the last typed grade, which you scanned. That's not what you want. It would be good, to save all values, which you get as input in an array or a list.
Also your codesnippet at the end
max = (grade<maxi) ? maxi : grade;
min = (grade>mini) ? mini : grade;
will just compare one grade. You need to compare all values, which you entered.
You could just put them in the for-loop.
gradeinput: You need to temporarily save your inputs in a datastructure like an array/list to use them in your program.
int x[counter];
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i);
x[i]=scanf("%d", &grade);
}
.. have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
This happens because OP's stdout is buffered and not one character at a time.
To insure output is seen before the scanf(), use fflush().
See What are the rules of automatic flushing stdout buffer in C?
printf("Enter number of grades: ");
fflush(stdout); // add
scanf("%d", &counter);
Rather than set the min = 1, set to a great value
maxi = 1;
mini = 1;
maxi = 0;
mini = 100;
// or
maxi = INT_MIN;
mini = INT_MAX;
Move the test for min/max in the loop to test each value and fold maxi, max into the same variable.
if (max > grade) max = grade;
if (min < grade) min = grade;
The first total + grade is a problem as total is uninitialized.
// int total; // sum of grades entered by user
int total = 0; // sum of grades entered by user
Unnecessary to calculate average each time though the loop. Sufficient to do so afterward.
Style: After the break; the else is not needed.
Good that code tests user input range. Yet the i-- is incorrect. If code is to break, just break. If code it to try again, the i-- makes sense, but then code should continue.
The comment // NOTE: integer division, not decimal is incorrect as (float) total / counter is FP division.
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n");
i--;
continue;
}
total = total + grade;
} // end for
average = (float) total / counter;
In general, casting should be avoided.
Advanced issue: Consider the situation if later on code was improved to handle a wider range of integers and used higher precision FP math.
The 1st form causes total to become a float (this could lose precision) and perhaps use float to calculate the quotient, even if average was a double. Of course the (float) cast could be edited to (double) as part of the upgrade, but that is a common failure about updates. Types may be changed, but their affected object uses are not fully vetted.
The 2nd form below causes total to become the same type as average and use the matching math for the type. Reduced changed needed as the types change. This form is also easier to review as one does not need to go back and check the FP type of average to see if a cast to float, double or even long double was needed.
average = (float) total / counter;
// or
average = total;
average /= counter;
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
You have two scanf before "Enter grade"
scanf("%d", &counter);
scanf("%d%d", &min, &max);
#include <stdio.h>
int main(void) {
int counter; // number of grade to be entered next
int grade; // grade value
int total=0; // sum of grades entered by user
float average; // average of grades
int i;
int max;
int min;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
} else {
if(i==1){
max = grade;
min = grade;
}
else{
max = (grade < max) ? max : grade;
min = (grade > min) ? min : grade;
}
total = total + grade;
average = (float) total / counter; // NOTE: integer division, not decimal
}
}
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
I've edited your Code as there were some mistakes. First, you were not initialising the total, which may make it take some garbage value. The second one is no need of using break as you are reducing the value of i.The third one is that you are updating the min and max outside the for loop, where the value of grade will be the last entered grade. And maxi and mini are not at all needed. The code was running perfectly without waiting for dummy values. Cheers!

How can I pull this off in C?

I have a program simulating a BMI (Body Mass Index) Calculator that takes in inputs from 10 users asking each user for a weight and a height, the program then calculates the BMI and prints the result of the computation in a formatted output.
Something like this:
USER BMI STATUS
1
:
10
So I thought of this, I would take in the inputs from the users first, then try to display the computation of the inputs in the above formatted way. Here's what I've tried to come up with which keeps asking the users for their weight and height until the 10th user.
#include <stdio.h>
#include <math.h>
int main(void) {
float weight_value = 0.0f;
float user_height = 0.0f;
float BMI = 0.0f;
char BMI_Status[30];
int i;
for ( i = 1; i <= 10; i++)
{
printf("Please enter your weight: ");
scanf("%f", &weight_value); //Reads in the user's weight
printf("Now enter your height: ");
scanf("%f", &user_height); //Reads in the user's height
BMI = weight_value / (user_height * user_height);
}
return 0;
}
The BMI Status is a string that displays different states of the computed BMI values, which are "Underweight", "Normal", "Overweight" for when the BMI value is within a given range.
The code snippet above is still incomplete as I'm still finding it difficult to add the rest of the code. Here are the issues I'm trying to solve.
How can I print out the BMI values after I have taken in the 10 inputs?
I have tried having a nested for loop that prints out the values, but this is illogical as there will now be an output of the BMI for every iteration of the outer for loop, so I'm guessing need a way to make scanf() hold the BMI values after the for loop's block.
How do I make the status strings appear?
I know there's no string datatype in C, so I'll have to declare a char array that holds the string for the status, but these are different strings for different statuses, and it has to be printed out for every line. I thought of having if else if else conditions for this but I just can't get the char array to work.
I already successfully wrote a code that prints out the user's BMI at every iteration, but this isn't how its supposed to be done.
Another thing I thought of was keeping the BMI values in an array of floating point numbers then displaying the values from the array in the above formatted way, but I'm still a bit sceptical about how I intend doing this.
Here the complete code to display the use of arrays to store the values. Your idea of using an if else for displaying how overweight a person is was good and so I implemented it.
#include <stdio.h>
#include <math.h>
int main(void) {
float weight_value[10]; //two arrays of ten elements each
float user_height[10];
float BMI = 0.0f;
char BMI_Status[30];
int i;
for ( i = 0; i < 10; i++) //the array starts from zero in C
{
printf("Please enter your weight: ");
scanf("%f", &weight_value[i]); //store the values in the array
printf("Now enter your height: ");
scanf("%f", &user_height[i]); //store the values in the array
}
printf("USER BMI\t\tSTATUS\n");
for( i = 0; i < 10; i++) //pass the array once again and calculate the needed values
{
BMI = weight_value[i] / (user_height[i] * user_height[i]);
printf("%d\t%f\t", i+1, BMI);
if(BMI < 30)
printf("Underweight\n");
else if(BMI < 50)
printf("Normal\n");
else
printf("Overweight\n");
}
return 0;
}
edited: skip to last
you will need to save them somewhere before you can read them to display it, you need to use an array to store all 10 inputs, at the moment every time a user inputs a data it will rewrite the data that was in the variable, which had the last user's data.
it needs to look like this:
...
float weight_value[10];
float user_height[10];
float BMI =[10];
char BMI_Status[30][3];
for ( int i = 1; i <= 10; i++)
{
printf("Please enter your weight: ");
scanf("%f", &weight_value[i]); //Reads in the user's weight
printf("Now enter your height: ");
scanf("%f", &user_height[i]); //Reads in the user's height
BMI[i] = weight_value / (user_height * user_height);
}
...
then to display you will need a loop like this
...
printf("user \t weight \t height \t BMi");
for ( int i = 1; i <= 10; i++)
{
printf("%d \t%f \t%f \t%s ", i,user_weight[i],user_height[i],BMI[i]);
}
...
i just re-read the question and realised i misread, however the last bit shows how you can read them from the array and display them.
The following code will store the weight and height of 4 users and print their BMI for an arbitrary number of thresholds (set to two in this case).
You can solve problem 1. by storing the weight and height into arrays (in the first loop).
You can then display a BMI status string by first defining a set of thresholds and a corresponding status string. In the second loop, for every user you compute and check whether the BMI value is under a given threshold and print its corresponding status string.
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#define USERS 4
#define THRESHOLDS 2
int main(void) {
float weight[USERS];
float height[USERS];
float BMI = 0.0f;
char * BMI_Status[THRESHOLDS+1] = {"Normal","Overweight","Obese"};
float thresholds[THRESHOLDS] = {10.0,20.0};
int i,j;
for ( i = 0; i < USERS; i++)
{
printf("Please enter your weight: ");
scanf("%f", &(weight[i])); //Reads in the user's weight
printf("Now enter your height: ");
scanf("%f", &(height[i])); //Reads in the user's height
}
for ( i = 0; i < USERS; i++)
{
BMI = weight[i]/(height[i]*height[i]);
printf("%d\t%f\t",i,BMI);
for ( j = 0 ; j < THRESHOLDS ; j++ ){
if ( BMI < thresholds[j]){
break;
}
}
printf("%s\n",BMI_Status[j]);
}
return 0;
}
Add an if statement in the for-loop
float BMI[10];
int j;
for ( i = 1; i <= 10; i++)
{
printf("Please enter your weight: ");
scanf("%f", &weight_value); //Reads in the user's weight
printf("Now enter your height: ");
scanf("%f", &user_height); //Reads in the user's height
BMI[i-1] = weight_value / (user_height * user_height);
if (i==10)
for (j=0; j<10; j++)
printf ("%d\n", BMI[j]);
}
Use char **a or char *a[]
for example:
char s[12] = "Hello World!";
char *p;
p = &s[0];
char *BMI_Status[30]; //declare 30 char*
BMI_Status[0] = "Fat";
BMI_Status[1] = "Thin";
...
//output
printf ("%s", BMI_Status[0]); //Fat

Working with scanf and loops in functions

I want to use a function to ask the user for a balance. If the balance is below 0 the user is prompted to enter a value above 0. Here is the code I have done so far:
#include <stdio.h>
#include <string.h>
float getPositiveValue();
int main()
{
float begbal;
begbal = getPositiveValue();
getPositiveValue();
printf("balance: %f\n", begbal);
return 0;
}
float getPositiveValue()
{
float money;
printf("Please enter the beginning balance: \n");
scanf("%f", &money);
if(money < 0)
{
printf("Enter a balance amount above 0:");
scanf("%f", &money);
}else{
}
}
I get the error "warning: control reaches end of non-void function". I know I need to end the else statement, but not sure what to put in there if they did enter a value above 0. Also, when the program is run it asks the user twice to enter the beginning balance for some reason. Seems like this should be a simple fix, for some reason I have trouble getting my head around functions heh.
Any help much appreciated.
revised working code(thanks):
#include <stdio.h>
#include <string.h>
float getPositiveValue();
int main()
{
float begbal;
begbal = getPositiveValue();
printf("balance: %f\n", begbal);
return 0;
}
float getPositiveValue()
{
float money;
printf("Please enter the beginning balance: \n");
scanf("%f", &money);
while(money < 0)
{
printf("Enter a balance amount above 0:");
scanf("%f", &money);
}
return money;
}
getPositiveValue() is supposed to return a value (float). You could add return money; before its closing }.
What if the user is particularly dense and doesn't enter a positive amount? Do you want to give them only one chance? If not, you probably want to use a while (money < 0.0) loop.
You need to return a float value, so in this case you can return money.
You are calling your function twice in the main function.
begbal = getPositiveValue();
getPositiveValue();
Just remove the last statement
"Also, when the program is run it asks the user twice to enter the
beginning balance for some reason."
because you have called function getPositiveValue() TWICE IN YOUR CODE
and your function needs to return the float value which is "money" in this case.
The user could persist in entering the wrong thing, so you need a loop to iterate till they get it right. Also, you need to return a value from this function.
float getPositiveValue()
{
float money;
fputs("Please enter the beginning balance: ", stdout);
for (;;) {
scanf("%f\n", &money);
if (money >= 0)
break;
fputs("Balance must be nonnegative.\n"
"Please enter the beginning balance: ", stdout);
}
return money;
}
But that's only the tip of the iceberg here. scanf should never be used, and floating-point numbers should not be used to keep track of money. What you should really be doing here is reading a line of text with getline (or fgets, if getline is unavailable), and parsing it with strtoul and custom logic, presumably as [$]dddd[.cc] (where square brackets indicate optional text), into a uint64_t value scaled to cents.
As the user may enter an invalid range (a negative number) or non-numeric text, need to consume offending input before next prompt.
float getPositiveValue() {
float money = 0.0;
printf("Enter a balance amount above 0:");
while ((scanf("%f", &money) != 1) || (money < 0)) {
int ch;
while (((ch = fgetc(stdin)) != '\n') && (c != EOF));
if (c == EOF) break;
printf("Enter a balance amount above 0:");
}
return money;
}

Resources