Learning C++ with help of Bruce Eckel “Thinking in C++”. Stuck in exercise 05 of chapter “Iostreams”:
Text of exercise
We know that setw( ) allows for a minimum of characters read in, but what if you wanted to read a
maximum? Write an effector that allows the user to specify a maximum number of characters to
extract. Have your effector also work for output, in such a way that output fields are truncated, if
necessary, to stay within width limits.
I understand how to create manipulators both without and with parameter (which one is called effectors in the book terminology). But do not understand how to limit maximum number of characters to extract. std::ios_base::width specifies the minimum number of characters.
Shoud I do some tricks with underlying streambuf object?
Its not a perfect solution (but I can’t think of another way at the moment without reading the iostream library).
Say you manipulator is:
When you write the stream operator(s) you write a slightly funky one that does not return an actual stream (but rather returns a stream with a wrapper around it).
Now you overload all the stream operator of this class to truncate their input before returning a normal stream object.
Then all you need is the generic overloads:
I would also add a conversion operator that converts MaxFieldWithStream to std::iostream automatically so that if it is passed to a function it still behaves like a stream (though it will loose its max width property).