Error in logic

This is a discussion on Error in logic within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> #include <math.h> int main(void) { char one; int counter; int userEntry; printf("\nEnter barcode: "); userEntry = scanf("%1c", ...

  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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,424
    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
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  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, 12: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21