Wednesday, 14 October 2009

Reading string via cin and flushing input buffers

The following program shows three different approaches to read string via Cin. It also shows two different approaches for flushing input buffer.






//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to read input string and to flush input buffer
#include<iostream>
#include<string>
#include <istream>
#include <limits>

using namespace
std;

int
main()
{

string s1;
cout << "\nAPPROACH 1" <<endl;
cout << "Input a string : ";
cin >> s1;
cout << "Entered string = " <<s1.c_str()<<endl;

//Lets flush the buffer from Approach 1 here
istream& in(cin);
in.ignore( numeric_limits<std::streamsize>::max(), '\n' );

cout << "\nAPPROACH 2" <<endl;
cout << "Input a string : ";
istreambuf_iterator<char> eos; // end-of-range iterator
istreambuf_iterator<char> iit (cin.rdbuf()); // stdin iterator
string s2;
while
(iit!=eos && *iit!='\n') s2+=*iit++;
cout << "Entered string = " << s2 << endl;

//Another approach for flushing the input
int ch;
while
((ch = cin.get()) != '\n' && ch != EOF);

cout << "\nAPPROACH 3" <<endl;
cout << "Input a string : ";
char
buf[BUFSIZ];
if
(cin.getline(buf, sizeof(buf)))
{

cout << "Entered string = " << buf << endl;
}


cout << endl;
return
0;
}







The output is as follows:



More information:

No comments:

Post a Comment