Thread: help with getchar()

  1. #1
    Registered User
    Join Date
    Mar 2016
    Posts
    2

    help with getchar()

    Hi, i wrote the program below:
    Code:
    #include<stdio.h>
    /*copy input to output; 1st version*/
       main()
       {
            int c;
            c=getchar();
            while(c!=EOF){
               printf("hello");           
               putchar(c);
               c=getchar();
            }
       }
    and i cannot understand why the message hello appear 2 times every time I insert a value with getchar(), can someone please explain why that happens, I expected the hello message appears one time with every time i insert a character.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,658
    Because the newline you press also counts in getchar()

    Try adding
    printf("Decimal value of ch=%d\n", c );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Mar 2016
    Posts
    2
    Quote Originally Posted by Salem View Post
    Because the newline you press also counts in getchar()

    Try adding
    printf("Decimal value of ch=%d\n", c );
    You are right, i added the printf and noticed that getchar() also gets the decimal=10 which is the line feed(Enter) value.
    Thank you.
    Last edited by nnannos; 03-20-2016 at 05:14 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. getchar()
    By bbray in forum C Programming
    Replies: 4
    Last Post: 09-08-2011, 05:13 AM
  2. Can someone try getchar() please?
    By znum in forum C Programming
    Replies: 3
    Last Post: 05-12-2008, 04:14 PM
  3. Using getchar()
    By countchocula in forum C Programming
    Replies: 13
    Last Post: 04-23-2008, 08:07 AM
  4. getchar & cin.get
    By 74466 in forum C++ Programming
    Replies: 4
    Last Post: 02-01-2006, 05:29 AM
  5. getchar
    By pktcperlc++java in forum C++ Programming
    Replies: 4
    Last Post: 02-13-2005, 08:31 PM