Solved

Input error checking, C programming

Posted on 2009-05-16
9
1,052 Views
Last Modified: 2012-05-07
I am very new to programming and having troubles. This is the second program I have written, aside from "Hello World". I got to this point by looking at other examples of user input error handling and taking those sections and adapting then into my program, sadly not fully understanding how they work, so now I am stuck.

My goal for this program is to have the user be able to enter the amount an item costs, then the program will print to the screen the sales tax on that items and the total amount of the sale for each of the three locations in the float section.

However, if a user enters a cost of .99 or 1.25, the program sees it as an error, and loops back asking for a positive integer. This is what I need to fix, the user needs to be able to enter, the cost without cents such as 125 or with cents such as 124.95.

Please help
//Author: David E. Berry

//Date: 15 May 2009, 23:38 this works for only positive numbers

//Revision: 2.0.9

//
 

#include <stdio.h>

#include <stdlib.h>
 
 

int main(int argc, char *argv[])
 

{
 

char input[BUFSIZ], *p;

long iAmountofSale;     /* Used to for long result*/
 
 
 

//Section for Intro Text

   

  printf("\n\tKudler Fine Foods Sales Tax and Total Calculation Program\n");

  printf("\n\tversion 2.0  Author: David E. Berry\n");

  printf("=========================================================\n");

  printf("\Sales Tax per Store location and Sales Total for that location\n\n");

  

//Section for numbers to plug into equations

  
 

  float iDelMarTaxRate = 0.0725;

  float iEncinitasTaxRate = 0.075;

  float iLaJollaTaxRate = 0.0775;

  float iTax_Result_DelMar = 0;

  float iTax_Result_Encinitas = 0;

  float iTax_Result_LaJolla = 0;

  float iTotal_Result_DelMar = 0;

  float iTotal_Result_Encinitas = 0;

  float iTotal_Result_LaJolla = 0;
 
 

     printf("Enter purchase amount: $");
 

//Error handling section to ensure positive interger for input
 

     for(;;)

     {        /* Infinite "for" loop until the user enters a positive number */
 

		fgets(input , sizeof(input), stdin);
 

		iAmountofSale = strtol(input , &p, 10);
 

		if(input[0] != '\n' && iAmountofSale > 0 && (*p == '\n' || *p == '\0')) break;

		

		else printf("Invalid input!\n\nPlease enter a positive integer for the amount: $"); /*Displays if the user did not enter a postive number*/
 

		iAmountofSale = 0;
 

      }

					

      printf("\nYou've entered the amount: $%ld\n", iAmountofSale); /*Displays what the number user input correctly*/
 
 

//Section for tax equations and results

    

               iTax_Result_DelMar = iAmountofSale * iDelMarTaxRate;

               printf("\nSales Tax for Del Mar is $%.2f\n", iTax_Result_DelMar);

  

               iTax_Result_Encinitas = iAmountofSale * iEncinitasTaxRate;

               printf("\nSales Tax Encinitas is $%.2f\n", iTax_Result_Encinitas);

  

               iTax_Result_LaJolla = iAmountofSale * iLaJollaTaxRate;

               printf("\nSales Tax La Jolla is $%.2f\n\n", iTax_Result_LaJolla);

               

               

//Section for Total Amount of sale equation and results 
 
 

               iTotal_Result_DelMar = iAmountofSale + iTax_Result_DelMar;

               printf("\nTotal Sale for Del Mar is $%.2f\n\n", iTotal_Result_DelMar);

  

               iTotal_Result_Encinitas = iAmountofSale + iTax_Result_Encinitas;

               printf("Total Sale for Encinitas is $%.2f\n\n", iTotal_Result_Encinitas);
 

               iTotal_Result_LaJolla = iAmountofSale + iTax_Result_LaJolla;

               printf("Total Sale for La Jolla is $%.2f\n\n", iTotal_Result_LaJolla);
 
 

          

     

 
 

  system("PAUSE");

  

  

  return 0;

}

Open in new window

0
Comment
Question by:Sunset_Vista
  • 4
  • 3
9 Comments
 
LVL 40

Accepted Solution

by:
evilrix earned 400 total points
Comment Utility
You data type for iAmountofSale is a long, which cannot represent floating point numbers so when you enter .99 it is truncated to 0. You need to change the type to be float or double. You'd also have to change line 49 from using strtol to using strtod instead.

http://www.cplusplus.com/reference/clibrary/cstdlib/strtod/

alternatively you could use scanf to capture the users input

float amount;
scanf("%f", &amount);

http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
0
 

Author Comment

by:Sunset_Vista
Comment Utility
evilrix, Thanks for telling me the why and suggesting a fix. However, the program will compile and run when I change iAmountofSale to float or double, but the program will still not let me enter a number decimal two numbers for iAmountofSale. When I changed strtol to strtod my Dev-C++ compiler program returned the error: In function 'main' too many argument to function 'strtod' [Build Error]

If I use scanf("%f", &amount); the program will let me enter negative numbers. That is why I moved to fgets . It there a way to write this using scanf to disallow character or negative numbers or a combination of both?
0
 
LVL 40

Assisted Solution

by:evilrix
evilrix earned 400 total points
Comment Utility
>> In function 'main' too many argument to function 'strtod' [Build Error]
Did you look at the docs for strtod? It takes 2 params (pointer to start and end of amount) and not 3 like strtol.
double strtod ( const char * str, char ** endptr );

>> If I use scanf("%f", &amount); the program will let me enter negative numbers
Parse the input and display an error if the input is negative (you are already doing this, no?)
0
 
LVL 40

Assisted Solution

by:evilrix
evilrix earned 400 total points
Comment Utility
>> pointer to start and end of amount
Sorry, just to clarify... endptr will end up pointing to the end of the amount after strtod has been called (I didn't make that very clear). Read the cplusplus docs for sull details.
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:Sunset_Vista
Comment Utility
evilrix,
I changed the type for iAmountofSale to double the fixed the strtod statement. But now it will not show the correct amount for what the user entered. I did go the references, as clear as they are it is still confusing to me. I have attached the part that is broken and a screen shot of how it looks when it runs.
 for(;;)

     {        /* Infinite "for" loop until the user enters a postive number */
 

		fgets(input , sizeof(input), stdin);
 

		iAmountofSale = strtod(input , &p); // was 	iAmountofSale = strtol(input , &p, 10);
 

		if(input[0] != '\n' && iAmountofSale > 0 && (*p == '\n' || *p == '\0')) break;

		

		else printf("Invalid input!\n\nPlease enter a positive integer for the amount: $"); /*Displays if the user did not enter a postive number*/
 

		iAmountofSale = 0;
 

      }

					

      printf("\nYou've entered the amount: $%ld\n", iAmountofSale); /*Displays what the number user input correctly*/

Open in new window

16-May-09-16-39-53.png
0
 
LVL 9

Assisted Solution

by:masheik
masheik earned 100 total points
Comment Utility
// printf("\nYou've entered the amount: $%ld\n", iAmountofSale); /*Displays what the number user input //correctly*/
you have to print the float/or double value so, use %f instead of %ld
0
 

Author Comment

by:Sunset_Vista
Comment Utility
masheik, Great catch! I changed it to a float and it works like I want it to now!! or least until I add more functions ;)

Both you and evilrix and answered all my questions that I had with this version of my little program. I am new to this forum, since you both gave answers to different parts of my question, how do I split the 'points' awarded?
0
 

Author Closing Comment

by:Sunset_Vista
Comment Utility
Evilrix gave accurate and complete information, but being a beginner to programming I was struggling to understand some of the answers. Masheik's answer was presented in a fashion that was easy to understand.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now