Re: noskipws and manipulator objects
Hello John!
On 23 Mar, 15:40, John L Fjellstad <john-n...@fjellstad.org> wrote:
I'm trying to understand manipulator objects, and especially noskipws.
std::noskipws is actually a function, not an object. It has a
declaration
like this:
namespace std { ios_base& noskipws(ios_base&); }
There are special overloads in the stream classes which take functions
like this or variations in the argument type (i.e. for std::basic_ios,
std::basic_istream, and std::basic_ostream) as argument and
essentially
just call them. But this has nothing to do with your question.
I have the following code:
############
std::istringstream stream("Hello World\nGoodbye Night");
std::string str;
stream >> std::noskipws >> str;
std::cout << str << std::flush;
############
My understanding is that this should print out
Hello World
Goodbye Night
This understanding is false! std::noskipws turns off automatic
skipping of
whitespace at the beginning of formatted input operations. It has no
effect
on the way the formatted input functions read from the stream. The way
std::string reads from a stream is to stop at the first whitespace
character
encountered: it essentially chops the input into individual words.
It seems your goal is to read the entire contents of a stream into a
string.
The idiomatic way to do this is, of course:
std::string str((std::istreambuf_iterator<char>(stream)),
std::istreambuf_iterator<char>());
(note: the extra parenthesis around the first argument are actually
required).
This may, however, be relatively slow compared to other approaches
like
std::ostringstream out;
out << stream.rdbuf();
std::string const& str = out.str();
Good luck!
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]