good way of clearing excess input?

This is a discussion on good way of clearing excess input? within the C++ Programming forums, part of the General Programming Boards category; Here is the code i used to prevent input from overflowing to subsequent cin request. No matter what is typed ...

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    203

    good way of clearing excess input?

    Here is the code i used to prevent input from overflowing to subsequent cin request. No matter what is typed in, only the first character is accepted. Everything after the first character is cleared until return/enter was pressed.

    char letter, letter2;
    cout << "Enter Letter: ";
    cin >> letter;
    for(; (cin.peek() != '\n') ;cin.ignore());

    is this a good way to clear a buffer of unknown size?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    while ( getchar() != '\n' );

    -Prelude
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Mar 2002
    Posts
    203
    tried that and i got an undefined variable error
    i thought i had mentioned i use MSVC++ 6.0
    *runs to his profile and adds his compiler*

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Don't forget to include <cstdio> or start using the current C++ header <iostream> else you won't be able to use getchar().

    -Prelude
    My best code is written with the delete key.

  5. #5
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,220
    This is non-ANSI, but it works for most:

    Code:
    #include <conio.h> 
    ...
    /* clear keyboard buffer */
    while(kbhit())
    {
     getch();
    }
    It might be while(!kbhit())

  6. #6
    Registered User
    Join Date
    Mar 2002
    Posts
    203
    how about for(char x; x != '\n';cin.get(x)); ?

    basicly i want to mimic a dummy getline but not have to send it a length.
    is there some kind of problem with using .peek() ?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem grabbing k/b input
    By falcon9 in forum C Programming
    Replies: 2
    Last Post: 10-28-2007, 12:47 PM
  2. Input statement problem
    By une in forum C Programming
    Replies: 3
    Last Post: 05-30-2007, 12:16 AM
  3. For loop problems, input please.
    By xIcyx in forum C Programming
    Replies: 2
    Last Post: 04-22-2007, 04:54 AM
  4. Clearing the Input buffer
    By Brain Cell in forum C Programming
    Replies: 5
    Last Post: 03-21-2004, 12:08 PM
  5. linked list recursive function spaghetti
    By ... in forum C++ Programming
    Replies: 4
    Last Post: 09-02-2003, 03:53 PM

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