Thread: Flushing extra characters

  1. #1
    Registered User
    Join Date
    Jun 2003

    Flushing extra characters

    What should I do if I only want to display the sentence'Please enter only one char' once? should the user enter more than one character?
    My program will repeat the above sentence countless times if enter a garbage like 'aksljdjlsadklsadklasdlkjaslkdjsakldjasljdlk'. I have read the faq but alas do not understand what is being said there.

    #include <iostream>
    #include <string>
    using namespace std;
    int main(void)
    	char c[10];
    	cout<<"Please enter only a character\n";
    	cin.get(c, 10 , '\n');
    		cout<<"Please enter only one char\n";
            return 0;
    Last edited by Mingzhi; 02-22-2004 at 05:05 AM.

  2. #2
    Registered User
    Join Date
    Feb 2004
    cin.ignore(80, '\n');
    As you know, cin.ignore() reads and discards a single character from cin. By passing the maximum number of characters you want to discard as the first argument, and the character to stop ignoring at as the second argument, you can throw away multiple characters per call. The above discards at most 80 characters and stops when a newline is read.

    A better solution is to not use an arbitrary value, instead opting for a portable calculation. The code is not too much more complicated.
    #include <limits>
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 02-21-2009, 02:55 AM
  2. Replies: 10
    Last Post: 07-10-2008, 03:45 PM
  3. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  4. Handling Extra Characters
    By hern in forum C Programming
    Replies: 3
    Last Post: 02-21-2004, 10:40 PM