Flushing extra characters

This is a discussion on Flushing extra characters within the C++ Programming forums, part of the General Programming Boards category; What should I do if I only want to display the sentence'Please enter only one char' once? should the user ...

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    13

    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.

    Code:
    #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<<strlen(c)<<endl;
    
    	if(strlen(c)>1)
    	{
    		cout<<"Please enter only one char\n";
    	}
    
    	cin.ignore();
    	cin.clear();
            return 0;
    }
    Last edited by Mingzhi; 02-22-2004 at 05:05 AM.

  2. #2
    Registered User
    Join Date
    Feb 2004
    Posts
    46
    Code:
    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.
    Code:
    #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, 04:45 PM
  3. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 05:54 PM
  4. Handling Extra Characters
    By hern in forum C Programming
    Replies: 3
    Last Post: 02-21-2004, 10:40 PM

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