Thread: How this function works?

  1. #1
    Registered User
    Join Date
    Sep 2014
    Posts
    74

    Exclamation How this function works?

    Hello guys, I wanted to understand how this function works. I have used it anyway without [roperly understanding its mechanism to remove a newline(\n) from the stream and get only one Character.

    Code:
    char getch(void)
    {
        char ch;
        ch = getchar();
        while(getchar()!='\n')
            ;
        return(ch);
    }

    Please explain :
    1) How this works? When is the original input taken?
    2) Why is the while loop empty?
    3) Do functions like scanf(),fgets() leave a trailing \n or \0?

    Thank You very much.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    This qualifies as a homework problem and, under this site's homework policy, you need to demonstrate some genuine effort of your own before expecting help.

    How about you offer explanations for those questions. We'll then give you pointers on whether you are right or wrong.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    What did you learn about getchar on your previous thread?
    http://cboard.cprogramming.com/c-pro...y-sorting.html
    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.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Sankait Laroiya
    1) How this works? When is the original input taken?
    The idea is to read a character, then read more characters and discard them until a newline is read. Then, the character that was first read is returned.

    Note that getchar returns an int, and it might return EOF, so it would be better to write:
    Code:
    char getch(void)
    {
        int ch, discard_ch;
        ch = getchar();
        while ((discard_ch = getchar()) != '\n' && discard_ch != EOF)
            ;
        return(ch);
    }
    Except that you have to consider that the character read by getchar is read as an unsigned char, so if char is signed and if the value read falls outside of the range of signed char, then the result of the conversion from int to char would be implementation defined.

    Quote Originally Posted by Sankait Laroiya
    2) Why is the while loop empty?
    Because there is no work that needs to be done in the loop body; the work is done in the loop condition.

    Quote Originally Posted by Sankait Laroiya
    3) Do functions like scanf(),fgets() leave a trailing \n or \0?
    This depends on the function. Read the relevant documentation.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Sep 2014
    Posts
    74
    Quote Originally Posted by grumpy View Post
    This qualifies as a homework problem and, under this site's homework policy, you need to demonstrate some genuine effort of your own before expecting help.

    How about you offer explanations for those questions. We'll then give you pointers on whether you are right or wrong.
    Its not homework. I am to start my first year in ECE in January 2015. I am learning independently.

  6. #6
    Registered User
    Join Date
    Sep 2014
    Posts
    74
    Quote Originally Posted by Salem View Post
    What did you learn about getchar on your previous thread?
    http://cboard.cprogramming.com/c-pro...y-sorting.html
    Well, that it leaves a trailing newline when we press enter to input a character and It gives a ASCII integer value for every character. Anything else you would like to add?

  7. #7
    Registered User
    Join Date
    Sep 2014
    Posts
    74
    Suppose I enter 's' the first getchar() reads it along with the newline (\n) then what does the getchar() in while loop does. I am not able to understand it. Is it like: the first getchar()'s newline is read by getchar() in the while loop's condition? and when it encounters a newline in the buffer how does it discard that newline? and in the end function returns 'ch' but ch is still equal to charaacter read+newline, so how it is removed?

    Please help me with this. I am stuck

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Sankait Laroiya
    Suppose I enter 's' the first getchar() reads it along with the newline (\n)
    No, the first getchar will read 's' only. A single call to getchar reads a single character, by definition.

    Quote Originally Posted by Sankait Laroiya
    ch is still equal to charaacter read+newline, so how it is removed?
    ch is only equal to the character read. The newline is discarded in the loop.
    Last edited by laserlight; 09-19-2014 at 02:34 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Can I just point out how rare it is to see laserlight make ANY mistake? :P
    Quote Originally Posted by laserlight
    [quot=Sankait Laroiya]...
    Fact - Beethoven wrote his first symphony in C

  10. #10
    Registered User
    Join Date
    Sep 2014
    Posts
    74
    Quote Originally Posted by laserlight View Post
    No, the first getchar will read 's' only. A single call to getchar reads a single character, by definition.


    ch is only equal to the character read. The newline is discarded in the loop.
    Okay. So, getchar() reads the character entered and the newline is added to the input stream.
    Alos, The while loop checks the stream with getchar() in its condition and if it encounters a newline then \n != \n becomes false so how the newline is discarded, the getchar() just eats it and doesn't care whether the condition is true or false?

    Thanks for still answering my questions

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Why don't you play with this code for a while
    Code:
    int ch;
    while ( (ch=getchar()) != EOF ) {
      printf("Decimal value of char=%d, visual representation=(%c)\n", ch, ch );
    }
    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.

  12. #12
    Registered User
    Join Date
    Sep 2014
    Posts
    74
    It helped bro. Thanks.

    So final question: When this becomes false while ( (ch=getchar()) != \n ) the loop breaks out and input buffer becomes completely empty? Like say we had S and \n in buffe, this while loop consumes everything in buffer?

    Thanks.

  13. #13
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    So final question: When this becomes false while ( (ch=getchar()) != \n ) the loop breaks out and input buffer becomes completely empty? Like say we had S and \n in buffe, this while loop consumes everything in buffer?
    Correct - assuming the '\n' that was read was the last character in the buffer.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Finding how a function works..
    By sdbuilt in forum C Programming
    Replies: 7
    Last Post: 09-28-2012, 12:34 PM
  2. How works the rand function?
    By angeloulivieri in forum C Programming
    Replies: 10
    Last Post: 06-13-2011, 05:20 PM
  3. Replies: 14
    Last Post: 03-02-2008, 01:27 PM
  4. Function works one time, and not another...
    By Captain Penguin in forum C++ Programming
    Replies: 3
    Last Post: 10-05-2002, 10:14 PM
  5. Can someone explain how this function works?
    By Drew in forum C++ Programming
    Replies: 1
    Last Post: 12-26-2001, 01:09 PM