Thread: Help! with character validity check

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    10

    Help! with character validity check

    I found this site while looking for any help to answer my issues with my program. I currently am a student at University of Phoenix, and this is my first programming class in C. Our teacher strongly encourages team and class cooperation so that our programs work. I have asked for help from my classmates, and no one has responded. So I am using my teachers advice and finding someone, anyone to help me.

    My program is supposed to do validity checks and I wanted mine to also prompt the user to re-enter the subtotal if a charcater was entered instead of a digit. Another thing I noticed is I have to hit the enter key twice before the rest of my program runs. Cannot figure that one out. Below is my problem program. Any help at this point would be greatly appreciated.

    Code:
    /* Kudler Food Tax Calculator */
    //by TDankert
    //July 30, 2007
    
    
    #include <stdio.h>
    #include <ctype.h>
    
    main()
    {
    
    //Variables Defined
    	float	fSubtotal, fDelmar, fEncinitas, fLajolla, fCheck;
    	char	cResponse;
    	
    	fSubtotal=0;
    	fCheck=0;
    	cResponse = '\0';
    
    //Taxrate Defined
    	fDelmar=.0725;
    	fEncinitas=.075;
    	fLajolla=.0775;
    
    //User Requirements
    printf("\nWelcome to Kudler Fine Foods,\n\nWe hope you enjoyed your shopping experience.\n");
    printf("\n\n\n\tPlease Enter your Subtotal: $");
    scanf("%f, %c", &fSubtotal, &cResponse);
    
    
    while (fSubtotal < fCheck){
    	printf("\nPlease Re-enter your Subtotal: $");
    	scanf("%f, %c", &fSubtotal, &cResponse );
    	}//end while loop
    	
    while (isdigit(cResponse)){
    	printf("\nPlease Re-enter your Subtotal: $");
    	scanf("%f, %c", &fSubtotal, &cResponse );
    	}//end while loop
    	
    //Del Mar Outputs
    	printf("\n\tTotal Sales Tax for Del Mar is $%.2f\n", fSubtotal*fDelmar);
    	printf("\tYour Del Mar Total is $%.2f\n", fSubtotal*fDelmar+fSubtotal);
    
    //Encinitas Outputs
    	printf("\n\tTotal Sales Tax for Encinitas is $%.2f\n", fSubtotal*fEncinitas);
    	printf("\tYour Encinitas Total is $%.2f\n\n", fSubtotal*fEncinitas+fSubtotal);
    
    //La Jolla Outputs
    	printf("\n\tTotal Sales Tax for La Jolla is $%.2f\n", fSubtotal*fLajolla);
    	printf("\tYour La Jolla Total is $%.2f\n\n", fSubtotal*fLajolla+fSubtotal);
    
    //Ending Outputs
    	printf("\n\nThank You for Shopping Kudler Fine Foods.\n");
    	printf("\n\tHave a Nice Day!");
    	
    	getch();
    
    }//End Tax Calculator

  2. #2
    Registered User
    Join Date
    Jul 2007
    Posts
    10

    I guess I could show what I have tried

    Right now I either end up in a continuous loop when entered like this:

    while (isdigit(cResponse)==0){

    the other way it does not recognize the command

    while (isdigit(cResponse)){

  3. #3
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    I had a poke around with it and I think I got it all working. First off I got rid of the comma in the "quoted" part of your scanf()'s like:
    Code:
    scanf("&#37;f %c", &fSubtotal, &cResponse );
    Then I changed your validity check to this:
    Code:
    while (!isdigit(cResponse)){  
            while(getchar() != '\n'); 
            printf("\nPlease Re-enter your Subtotal: $");
    	scanf("%f %c", &fSubtotal, &cResponse );
    	}
    Instead of running while cResponse is a digit it now runs when its not a digit.

    Edit: I also added this line:
    Code:
    while(getchar() != '\n');
    to flush the input buffer which stops the prog going into an infinite loop sometimes when bad input. is entered
    Last edited by mike_g; 07-29-2007 at 02:40 PM.

  4. #4
    Registered User
    Join Date
    Jul 2007
    Posts
    10
    Thanks Mike,

    I will give this a try. I have spent hours trying to get this program to work. And of course the text we use is useless. ;-)

    Tamara

  5. #5
    Registered User
    Join Date
    Jul 2007
    Posts
    10
    Mike,

    Well it catches the charcter now and prompts for a re-enter. But now it will not recognize the digits that are needed to do the tax calculation. With this change the program, whether it is a character or a digit prompts user to re-enter subtotal.

    The program should automatically run the rest of the program if a digit was entered. If it is a negative number or character should prompt and then once a number is entered continue on.
    Last edited by Tdankert; 07-29-2007 at 03:18 PM.

  6. #6
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    fSubtotal should accept a float as long as its not negative. Thats the only input that has an effect on the calculation.

    Heres the code I got:
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    int main()
    {
    
    //Variables Defined
    	float	fSubtotal, fDelmar, fEncinitas, fLajolla, fCheck;
    	char	cResponse;
    	
    	fSubtotal=0;
    	fCheck=0;
    	cResponse = '\0';
    
    //Taxrate Defined
    	fDelmar=.0725;
    	fEncinitas=.075;
    	fLajolla=.0775;
    
    //User Requirements
    printf("\nWelcome to Kudler Fine Foods,\n\nWe hope you enjoyed your shopping experience.\n");
    printf("\n\n\n\tPlease Enter your Subtotal: $");
    scanf("%f %c", &fSubtotal, &cResponse);
    
    
    while (fSubtotal < fCheck){
        while(getchar() != '\n'); 
    	printf("\nPlease Re-enter your Subtotal: $");
    	scanf("%f %c", &fSubtotal, &cResponse );
    	}//end while loop
    	
    while (!isdigit(cResponse)){  
        while(getchar() != '\n'); 
        printf("\nPlease Re-enter your Subtotal: $");
        scanf("%f %c", &fSubtotal, &cResponse );
    	}
    	
    //Del Mar Outputs
    	printf("\n\tTotal Sales Tax for Del Mar is $%.2f\n", fSubtotal*fDelmar);
    	printf("\tYour Del Mar Total is $%.2f\n", fSubtotal*fDelmar+fSubtotal);
    
    //Encinitas Outputs
    	printf("\n\tTotal Sales Tax for Encinitas is $%.2f\n", fSubtotal*fEncinitas);
    	printf("\tYour Encinitas Total is $%.2f\n\n", fSubtotal*fEncinitas+fSubtotal);
    
    //La Jolla Outputs
    	printf("\n\tTotal Sales Tax for La Jolla is $%.2f\n", fSubtotal*fLajolla);
    	printf("\tYour La Jolla Total is $%.2f\n\n", fSubtotal*fLajolla+fSubtotal);
    
    //Ending Outputs
    	printf("\n\nThank You for Shopping Kudler Fine Foods.\n");
    	printf("\n\tHave a Nice Day!");
    	
    	getch();
    
    }//End Tax Calculator
    Does this not do what you want? It seems to work for me.

    Oh and btw its best to use 'int main()'.

  7. #7
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Code:
        getch();
        return 0;
    }//End Tax Calculator

  8. #8
    Registered User
    Join Date
    Jul 2007
    Posts
    10
    When I run the program I need it to calculate the tax when a digit is entered. I am using Miracle C to run these programs if that makes a difference.

    Mike I made the changes you mentioned when I execute the program and I put in the number and hit enter it just moves to the next line and I do not receive any calculations at all. When I put in a character it will prompt for re-entering subtotal, but then when number is entered it does not display the tax, and total.

  9. #9
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    Are you by any chance hitting enter after you type enter the first number? It sounds like you are. You should enter a floating point value followed by a space followed by a digit. That should work.

    [edit]It seems what I just said should not make a difference actually.[/edit]
    Last edited by mike_g; 07-29-2007 at 04:31 PM.

  10. #10
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Your problem is probably caused by the fact that scanf() skips any whitespaces. To match "%c", you need to type something that isn't a whitespace, so you would probably get past your scanf by typing "4.50a". Unfortunately, that will fail your "isdigit" check, so you're stuck in a loop here.

    I'm a little bit uncertain as to exactly what you are trying to achieve here - I understand the purpose of this:
    Code:
    while (fSubtotal < fCheck){
        while(getchar() != '\n'); 
    	printf("\nPlease Re-enter your Subtotal: $");
    	scanf("%f %c", &fSubtotal, &cResponse );
    	}//end while loop
    But I'm not sure what this bit is meant to achieve:
    Code:
    while (!isdigit(cResponse)){  
        while(getchar() != '\n'); 
        printf("\nPlease Re-enter your Subtotal: $");
        scanf("%f %c", &fSubtotal, &cResponse );
    	}
    I also don't really understand why you try to read another character after your %f - what exactly do you intend "cResponse" to contain?

    --
    Mats

  11. #11
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    Your problem is probably caused by the fact that scanf() skips any whitespaces. To match "&#37;c", you need to type something that isn't a whitespace, so you would probably get past your scanf by typing "4.50a". Unfortunately, that will fail your "isdigit" check, so you're stuck in a loop here.
    I dident know that. For me it dosent seem like that isnt the case, but I might be missing something here. For example if I add these two lines at the end of the prog:
    Code:
    printf("\n%c", cResponse);
    printf("\n%f", fSubtotal);
    Then use this test data:
    Code:
    45.5 5
    I get this output at the end:
    Code:
    5
    45.500000
    So it seems as if the space seperates the two variables. Maybe this is something that just happens to me for some reason? I don't really know a lot about scanf(). I generally use fgets() for anything more than a single number input.

  12. #12
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Mike G:

    It works just fine if you enter "45.5 5", yes, because %c is matched by a 5. But if you enter "45.5 " or "45.5 ", scanf() will still want "more" input to satisfy "%c". Hitting enter doesn't work either, becuase for scanf() that is just another whitespace, and not "good enough" to fill in a "%c".

    But I don't think the original poster wanted to have "45.5 5" as input, but rather "45.5" on it's own. So the 'extra' "%c" is actually causing a problem.

    --
    Mats

  13. #13
    Registered User
    Join Date
    Jul 2007
    Posts
    10
    Ok. I changed the code to this
    Code:
    while (fSubtotal < fCheck){
    	printf("\nPlease Re-enter your Subtotal: $");
    	scanf("%f", &fSubtotal);
    	}//end while loop
    	
    while ( !isdigit(cResponse)){  
    	printf("\nPlease Re-enter your Subtotal: $");
    	scanf("%c", &cResponse);
    	}//end while loop
    It catches the character and now says 3 times to re-enter a subtotal. I can then enter a number but it will do any calculations just returns zero's. I've attached my results in word.doc.

  14. #14
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    What does the first scanf() line look like?

    If you start with a "cResponse" that is "\0", that will catch on "while(!isdigit(cResponse)".

    I would also suggest that you do something like this:
    Code:
       int valid; 
    ...
       do {
          printf("Enter subtotal:"
          valid = 1;   // Valid until proven invalid - can be done the other way around too. 
          scanf("%f", &fSubTotal);
          if ( ... some checking ...)
             valid = 0;
          if ( ... some other check ... )
             valid = 0;
          if (!valid)
             printf("Sorry, not valid, try again\n");
       } while (!valid);
    The reason I say that is that if you enter a value that is caught in the second check (!isdigit), and you then enter a negative number, it will happily accept that, since the checek against negative numbers has already been done. So by making it one single input, and doing ALL checks every time, you can ensure that whatever conditions you've applied are actually respected.

    Another solution would be to read the value in as a string (e.g. with "fgets(sSubtotal, sizeof sSubtotal, stdin)"), validate that it looks like a valid "amount of dollars" (that is, it contains only some digits (may be none, if the total is less than a whole dollar), and optionally a dot and two more digits), then try to convert it to a floating point number, check that the conversion is a success and perform the calculation after that.

    One way to convert a string to float is:
    Code:
      if (sscanf(sSubTotal, "%f", &fSubTotal) != 1)  valid = 0;
    Another option is "strtof", which also allows you to check if the number was completely "accepted" by checking what the endptr points to after the conversion - if it's at a "\n" or "\0", it went OK - if not, whatever endptr points at is "erroneous number content", e.g. a string like "4.5abc" would make endpointer point to "abc" within the string.

    strtof docs:
    http://linux.about.com/library/cmd/blcmdl3_strtof.htm

    --
    Mats

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    My visual studio .net doesn't support strtof, but by using "strtod", I can make it do the same thing, except that I get a double precision float. You can easily use double for all calculations, or you can convert double to float.

    --
    Mats

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Not working in linux...
    By mramazing in forum C++ Programming
    Replies: 6
    Last Post: 01-08-2009, 02:18 AM
  2. allegro issues
    By mramazing in forum C++ Programming
    Replies: 1
    Last Post: 01-07-2009, 11:56 PM
  3. HELP!!!!emergency ~expert please help
    By unknowppl in forum C Programming
    Replies: 1
    Last Post: 08-19-2008, 07:35 AM
  4. syntax error when defining vectors
    By starkhorn in forum C++ Programming
    Replies: 5
    Last Post: 09-22-2004, 12:46 PM
  5. Pointer validity check
    By Carlos in forum Windows Programming
    Replies: 6
    Last Post: 12-11-2003, 03:40 AM