Thread: getchar and putchar

  1. #1
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804

    getchar and putchar

    halo all,
    i've just started with K&R and got confused in this code.
    Code:
    #include<stdio.h>
    #include<conio.h>
    int main(void)
    {
    clrscr();
    int c;
    c=getchar();
    while(c!=EOF)
    {
    putchar(c);
    c=getchar();
    }
    getch();
    return 0;
    }
    i dont understand how this program runs.for eg. if i give as input the string "i am new to c"(without double quotes) and then press enter the output it gives is "i am new to c" but what i think the output should be "i" because in my opinion the code first looks for an input ,then checks it against EOF and if the character is not EOF then it should print the first character and again repeats the process.
    also if i run this code and give the same input(i am new to c) the output is what i expect i.e "i".
    Code:
    c=getchar();
    putchar(c);

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    and what about while loop?

    what is the purpose of it?
    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
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    that's why i said it should repeat the process because of the while loop only

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Because getchar() will "pull" keystrokes, if any are waiting in the keyboard buffer. You have a small string of char's waiting for it, so it pulls them, then prints them, one after the other.

    The second example obviously can't do that, since it has no loop.

    Want to see how big your keyboard buffer really is? See how big a string you can put into the string, before your mobo starts complaining.

  5. #5
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    Thanks adak you solved my confusion.thanks a lot.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can someone try getchar() please?
    By znum in forum C Programming
    Replies: 3
    Last Post: 05-12-2008, 04:14 PM
  2. Calculator using getchar, putchar
    By arlen20002000 in forum C Programming
    Replies: 5
    Last Post: 03-26-2008, 10:37 AM
  3. need help please! getchar, putchar, etc.
    By sue in forum C Programming
    Replies: 1
    Last Post: 03-21-2003, 08:40 PM
  4. Replies: 2
    Last Post: 01-10-2002, 07:42 PM