Wednesday, 15 January 2014

c++ - cin, whitespaces and 'buffering' -



c++ - cin, whitespaces and 'buffering' -

so wrote 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; homecoming 0; }

i type in 'word1 word2 word3' on 1 line , output expected is

word1 word2 word3

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

which brings me question. cin runs out of things read stdin, query user (stdin).

i way observe whether cin read stdin buffer or query user.

i know simple question, homework... , i'm in massive work-induced time cruch, kudos whoever shares power!

what you're trying can't done operator>> because doesn't distinguish between different kinds of whitespace. @ implementation in favorite c++ standard library, next gcc 4.7.2's (bits/basic_string.tcc):

995 // 21.3.7.9 basic_string::getline , 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 can see, (line 1029) stops on whitespace encountered ( see http://en.cppreference.com/w/cpp/locale/ctype_base ctype_base::space).

what want hence utilize getline (which stops when encounters newline) , extract via stringstream:

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

c++ stdin cin

No comments:

Post a Comment