user1833028
user1833028

Reputation: 943

cin, whitespaces and 'buffering'

So I wrote this very simple program:

#include <iostream>
#include <string>
using namespace std;

int main()
{
string input;

cin >> input;
cout<< input<<endl;
cin >> input;
cout<< input<<endl;
cin >> input;
cout<< input<<endl;
return 0;
}

I type in 'word1 word2 word3' on one line and the output as expected is

word1
word2
word3

now of course, I could've gotten the same output as for (int i=0; i <3; i++){cin>>input; cout << input<<endl;}.

Which brings me to my question. As soon as cin runs out of things to read from stdin, it will query the user (stdin).

I a way to detect whether cin will read something from the stdin buffer or query the user.

I know its a simple question, but its for homework... and I'm in a massive work-induced time cruch, so kudos to whoever shares the power!

Upvotes: 1

Views: 238

Answers (1)

us2012
us2012

Reputation: 16253

What you're trying to do can't be done with operator>> only because it doesn't distinguish between different kinds of whitespace. Look at the implementation in your favorite C++ standard library, the following is from gcc 4.7.2's (bits/basic_string.tcc):

 995   // 21.3.7.9 basic_string::getline and operators
 996   template<typename _CharT, typename _Traits, typename _Alloc>
 997     basic_istream<_CharT, _Traits>&
 998     operator>>(basic_istream<_CharT, _Traits>& __in,
 999            basic_string<_CharT, _Traits, _Alloc>& __str)
1000     {
...
1027           while (__extracted < __n
1028              && !_Traits::eq_int_type(__c, __eof)
1029              && !__ct.is(__ctype_base::space,
1030                  _Traits::to_char_type(__c)))
1031         {

As you can see, (line 1029) this stops on all whitespace encountered ( see http://en.cppreference.com/w/cpp/locale/ctype_base for ctype_base::space).

What you want to do is therefore to use getline (which stops when it encounters a newline) and extract via a stringstream:

getline(cin,mystring);
stringstream str(mystring);
while (str >> token) {
  cout << token << '\n';
}

Upvotes: 2

Related Questions