Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

cin.getline - flushing input stream

  • 08-12-2004 4:04pm
    #1
    Closed Accounts Posts: 1,567 ✭✭✭


    How do some of you using cin.getline do away with excess characters.
    I have this problem where i get a name of person from the console,
    something like below, and the max size of input buffer is 20 bytes.
    	for(int i = 0; i < 3; i++)
    	{
    		gotoxy(1,7); cout << "Enter user number " << (i + 1) << ":";
    		cin.getline(user_struct[i].user_name,20,'\n');
    	}
    

    The problem is that, if the person enters 30 characters, the
    next call to cin.getline returns those 10 characters after the first 20.
    I want to avoid this.

    Is there some way to flush these out of the input stream, do away with them?
    before the next call?
    I asked some programmer already, and he says "its not important",
    i think maybe because he didn't know.
    but i'd like to know anyway.


Comments

  • Registered Users, Registered Users 2 Posts: 6,570 ✭✭✭daymobrew


    Two options (though I don't know much istream):
    1) Make the streamsize (2nd param) bigger than the data will ever be.
    Then extract the required chars from that (strncpy or the like).

    2) istream::ignore (Extracts characters from input stream and discards them)
    http://www.cplusplus.com/ref/iostream/istream/ignore.html
    Looks like you can read chars up to the specified EOL char ('\n' presumably).
    This will 'eat' the unwanted chars.

    Of course, both of these solutions will suffer from buffer overflow errors if too much data is thrown at them.


  • Registered Users, Registered Users 2 Posts: 950 ✭✭✭jessy


    look into the function fflush();


  • Closed Accounts Posts: 1,567 ✭✭✭Martyr


    Thanks for input lads.
    I looked around for info on this.

    Some suggestions were to repeatedly use getchar() or cin.getc()
    until a newline..but i didn't think this was much good.

    fflush() doesn't work apparently.
    i tried something like fflush(stdin);

    I found that cin.sync() was best solution to problem.
    you just call it afterwards and it clears any excess characters
    in the istream.
    char buffer[5]
    
    cin.getline(buffer,5);
    cin.sync();
    


Advertisement