Thread: Error in logic

  1. #1
    Registered User
    Join Date
    Mar 2010
    Location
    Australia
    Posts
    174

    Error in logic

    Code:
    #include <stdio.h>
    #include <math.h>
    
    int main(void) {
        char one;
            int counter;
            int userEntry;
    
        printf("\nEnter barcode: ");
            userEntry =
    scanf("%1c", &one);
    
            counter = 1;
            while (counter < 3) {
                    if ( one < '0' || one > '9') {
                            one = getchar ();
                            counter = counter + 1;
                            printf("1\n");
                    } else {
                            counter = counter + 1;
                            printf("2\n");
                    }
            }
            if (one >= '0' && one <= '9') {
                    one = getchar ();
                    printf("3\n");
            } else {
                    printf("4\n");
            }
    return 0;
    }
    When I type in a number, it gives me 2 2 4 like it should, but when I type in a character like 'a' it doesn't give me 1 1 4 which I would expect. It instead gives me a 1 and then doesn't finish the program. Where is the problem?

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,794
    when you enter 'a' and press enter
    the buffer contains 2 chars 'a' '\n'
    first is read by scanf
    second is read by getchar and first 1 is printed
    after that program loops to next getchar and waits for the next input
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

  3. #3
    Registered User
    Join Date
    Mar 2010
    Location
    Australia
    Posts
    174
    Ok thanks for that

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Handling logic and draw cycles
    By DavidP in forum Game Programming
    Replies: 1
    Last Post: 07-25-2009, 10:15 AM
  2. Digital Logic
    By strokebow in forum Tech Board
    Replies: 3
    Last Post: 12-09-2006, 01:05 PM
  3. Logic
    By LordBronz in forum C++ Programming
    Replies: 6
    Last Post: 05-23-2006, 05:41 PM
  4. Actors, cues, event based logic.
    By Shamino in forum Game Programming
    Replies: 2
    Last Post: 04-27-2006, 10:58 PM