Need help with scanf

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • alexanderkwok17
    New Member
    • Aug 2010
    • 2

    Need help with scanf

    I try to write a program that identify amounts of sale, and i also need to show an error message when a character is entered;
    so i try the following:
    Code:
    #include <stdio.h>
    
    int main(int argc, char **argv){
        int sale1, sale2;
        char c1;
            printf("Amount of Sale (inclusive of GST):");
            scanf("%d.%d", &sale1, &sale2);
            scanf("%c", &c1);
            if (c1 >= 'A' && c1 <= 'Z'){
            printf("Input error\n");
            return 0;
            }else if (c1 >= 'a' && c1 <= 'z'){
            printf("Input error\n");
            return 0;
            }
    .....
    but when i run the program, if i type
    a
    it will skip a line and wait for another input. so is there a way to correct this error??
    And is it possible to do this just with int, because my teacher want us to do it with just int,(which is without using char).
    Last edited by alexanderkwok17; Aug 3 '10, 11:37 AM. Reason: additional question
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    scanf will return 0 if the type of the data entered does not match the type of the variable where it is to be stored.

    In your case, the a is not an integer. scanf terminates. The next scanf resumes after the a.

    To fix the error you can put scanf for the int inside a loop that will continue until scanf returns non-zero.

    Comment

    • alexanderkwok17
      New Member
      • Aug 2010
      • 2

      #3
      I think i know how to do it now,
      i just initialise the value of a to a nnumber,
      and then put it in the if statement, so that if a is inputed then a will be the initialise value as well.
      And thanks anyways

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        The initial value of a is not important. What is important is that you check to see that scanf worked correctly:


        Code:
        int a;
        int rval;
        
            rval = scanf("%d", &a);
            if (rval == 0)
            {
                printf("scanf failed\n");
                return; 
            }
            /* a has the entered value here */

        Comment

        Working...