Thread: A getchar problem

  1. #1
    Registered User ch4's Avatar
    Join Date
    Jan 2007
    Posts
    154

    A getchar problem

    This is stupid code i made.
    There is a problem.If i delete one of the "getchar()'s" the program doesn't work.
    Can anyone explain why?

    Code:
    #include <stdio.h>
    int main (void)
    {
        int a,b,c;
        float d;
        
        printf("How many apples did you eat?");
        scanf("%d",&a);
        if(a>0){
                printf("How many were there?");
                scanf("%d",&b);
                printf("How many apples?");
                scanf("%d",&c);
                d=b/a;
                if (a>d){
                         printf("You are fat!");
                        }            
                }
        else
            printf("Did you drink?");
    getchar();
    getchar();
    return 0;
    }

  2. #2
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    The program should still work, it will just quit before you get a chance to see the output. The first getchar() absorbs the \n character from when you hit return at your scanf(), the second then waits for another character. Without the second getchar, the program just ends without pausing.

  3. #3
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Define "doesn't work".

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM
  2. getchar() problem
    By jlharrison in forum C Programming
    Replies: 6
    Last Post: 01-25-2006, 02:49 PM
  3. problem with parser code
    By ssharish2005 in forum C Programming
    Replies: 2
    Last Post: 12-02-2005, 07:38 AM
  4. Replies: 5
    Last Post: 11-07-2005, 11:34 PM