How to flush standard input stream in C++?


Ans: Consider the following code:

void main( )

{

char str1[10], str2[10] ;

cin.getline ( str1, 9 ) ;

cin.getline ( str2, 9 ) ;

cout << str1 << endl << str2 ;

}

If you run this program you will find that you are able to scan only one string from keyboard and when you hit Enter key to scan the second string the program returns to the edit window. This is because when you hit Enter key the ‘Enter’ character gets stored in the keyboard buffer and when the second getline( ) goes to work this enter is picked up and gets stored in the second string. Thus the second cin statement doesn’t wait for the user to enter the string. To avoid such a situation we use fflush ( stdin ) statement in C to flush the input buffer. In C++ use the following function before cin statement to flush the buffer:

cin.ignore( )

It's very calm over here, why not leave a comment?

Leave a Reply




Categories

UserOnline

Improve the web with Nofollow Reciprocity.

Powered by Yahoo! Answers