I don't understand "while (getchar() != '\n');"

This is a discussion on I don't understand "while (getchar() != '\n');" within the C++ Programming forums, part of the General Programming Boards category; Hi guys, I'm one of the many who encountered a problem with the getchar() function picking up the newline '\n' ...

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    4

    I don't understand "while (getchar() != '\n');"

    Hi guys,

    I'm one of the many who encountered a problem with the getchar() function picking up the newline '\n' as an input on subsequent getchar() statements.

    I googled and found the following solution such that the second getchar() doesn't get a newline as an input and it works.

    Code:
    input = getchar();
    while (getchar() != '\n');
    input = getchar();
    However, I don't get how the while (getchar() != '\n'); eliminates any newlines such that the following getchar() doesn't capture the newline as an entry.

    I tried searching for this on Google but I didn't find any answers(that I understand) regarding this matter. :/

    Can anyone explain, please? Thanks! And please keep in mind I only started programming 4 weeks ago which means I'm like absolutely noobish.

  2. #2
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,614
    getchar fetches a character from the input stream every time it's called. So the loop basically does this:

    Call getchar.
    Compare getchar to '\n'.
    If not equal, break the loop.

    Remember that the last character in the input buffer will be the newline, so that's why it works.

    Example:
    Left in input buffer: Hello World\n
    Loop calls getchar.
    Left in input buffer: ello World\n
    ...
    Loop calls getchar.
    Left in input buffer: \n
    Loop calls getchar.
    getchar returns '\n', so loop breaks.
    Left in input buffer: nothing.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #3
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,706
    OK, forget about getchar for a moment, just pretend that c is its return value.

    while( c != '\n' ) ;

    When is this not true? If c=='\n', therefore, getchar read a newline. Under normal circumstances there wouldn't be anything to read after that, so the next getchar waits for input.
    Last edited by whiteflags; 09-06-2009 at 10:25 AM.

  4. #4
    Registered User
    Join Date
    Sep 2009
    Posts
    4
    Ahh... So getchar() reads from left to right... I was actually sort of thinking it read the string from right to left... XD So that's why. And truly, thanks alot! You guys answered a question that's been ailing me for 2 days in just 10 minutes o.o
    Last edited by valedor; 09-06-2009 at 10:30 AM.

  5. #5
    Registered User
    Join Date
    Sep 2009
    Posts
    4
    Another solution I found involves using scanf:

    Code:
    scanf("%c",&input);
    scanf(" %c",&input);
    How exactly does the space actually eliminate the "\n" entered anyway? o.o I read on Google, and they just say they just "sort of" cancel each other out. Not very clear :/

  6. #6
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,706
    Format strings can be a mess, but if you can keep it simple they're easy enough to use. In the second statement, the format string has a whitespace character, which communicates to scanf to ignore any and all such characters. Other conversions don't need this kind of treatment. scanf("%d%s", userid, name); would work the same with "%d %s" as the first argument, but with chars, the ignoring of whitespace is suppressed.

  7. #7
    i've lost my mind
    Join Date
    Jun 2008
    Posts
    26
    this is what a\nmultiline file actually\nlooks like when you access it programatically\n

    this is what a
    multiline file actually
    looks like when something like
    notepad opens the file


    there are many other escape characters, another you might find in a text file is \t for tabs. etc...

    IF (TRUE) continue ELSE gtfo.

    LINE #1
    't' != '\n' - TRUE
    'h' != '\n' - TRUE
    'i' != '\n' - TRUE
    's' != '\n' - TRUE
    ' ' != '\n' - TRUE
    'i' != '\n' - TRUE
    's' != '\n' - TRUE
    // ...
    '\n' != '\n' - FALSE *** GTFO! >:]

    LINE #2
    't' != '\n' - TRUE
    'h' != '\n' - TRUE
    // ...
    '\n' != '\n' - FALSE *** GTFO! >:]

    ... until end of file.
    Last edited by gltiich; 09-08-2009 at 09:07 AM.

  8. #8
    Registered User
    Join Date
    Sep 2009
    Posts
    4
    Thanks. I understand while(getchar() != '\n'); much better now

    I also ran a test on scanf such that I replace the front part of the input specifier with different whitespace characters.

    For example:
    scanf("\n%c",&input);
    scanf("\t%c",&input);
    scanf("\f%c",&input);

    and so on...

    They seem to do the trick for telling C++ to skip over any and all whitespaces behind the character. I'm assuming that putting a whitespace in front of the input specifier instructs C++ to read all whitespace characters then look for a %c character to assign to the input variable.

    Is my assumption right? Or did I misinterpret your explanation wrongly, whiteflags?

    And really, many thanks for the help!

  9. #9
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,614
    Don't use scanf in C++. Use cin >>.
    To clear the input buffer, do
    Code:
    std::cin.clear(std::numerical_limits<int>::max());
    (I believe.)
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    No, no, that's all wrong! :P Never use "int" when you can typedef another more complicated name and use that instead.
    Code:
    std::cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
    You also need to include <limits> and <ios> (along with <iostream> if you're clearing std::cin).
    why do some programs work on some compliers while others dont?
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  11. #11
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,614
    I never use it enough to know what it accepts or the names of arguments of those stuff... so yeah, don't blame my bad memory. I did try...
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Apr 2006
    Posts
    2,036
    Quote Originally Posted by dwks View Post
    No, no, that's all wrong! :P Never use "int" when you can typedef another more complicated name and use that instead.
    The alternative is of course to save 36 characters and use INT_MAX from <climits>.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  13. #13
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    My point was that std::streamsize isn't guaranteed to be of type int (at least as far as I know).

    But yeah, you could just use INT_MAX. That's sufficiently high enough that it would almost always work . . . .
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  14. #14
    Registered User
    Join Date
    Apr 2006
    Posts
    2,036
    Yeah, I'm aware. Depending on the context, and the urgency of what I'm trying to do, I'd either use the streamsize version or INT_MAX.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. getchar() problem
    By jlharrison in forum C Programming
    Replies: 6
    Last Post: 01-25-2006, 01:49 PM
  2. getchar buffer size
    By oncemyway in forum C Programming
    Replies: 3
    Last Post: 08-02-2005, 12:49 AM
  3. getchar() problem from K&R book
    By anemicrose in forum C Programming
    Replies: 13
    Last Post: 04-04-2004, 11:06 PM
  4. help with getchar lol
    By Taco Grande in forum C Programming
    Replies: 5
    Last Post: 03-18-2003, 08:25 PM
  5. Can anybody take a look at this?
    By TerryBogard in forum C Programming
    Replies: 10
    Last Post: 11-21-2002, 12:11 PM

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