I have a partial solution. The problem with a max manipulator is that it requires fiddling with the private data of ios_base. setw() calls ios_base::width(). You would have to derive from ios_base, or more likely, from basic_ostream to add these features.
I went another way.
What I did was go to the C/C++ Articles section and copied out the code for a simple Singleton object. This object contains the max field width. I added methods to set/get this value.
Next, I wrote an operator<<(ostream&, const string&). But this one is not in the std namespace so it is differentiable from std::operator<<(ostream&, const string&). Further, is occurs after the #include <iostream> so the compiler will prefer it to the one in std. My operator<< for string uses the singleton to determine how many characters of the string to display.
It's not a manipulator but it does get your desired output.
-
#include <iostream>
-
using namespace std;
-
-
class SysParms
-
{
-
private:
-
streamsize maxwidth;
-
SysParms(const SysParms&); //Prevents making a copy
-
-
protected:
-
SysParms(); //Only a SysParms member can call this
-
//Prevents a user from creating singleton objects
-
virtual ~SysParms(); //Prevents just anyone from deleting the singleton
-
-
public:
-
-
-
//The "official" access point.
-
static SysParms* Instance();
-
void MaxWidth(streamsize arg);
-
streamsize GetMaxWidth();
-
-
};
-
-
-
namespace
-
{
-
SysParms* instance = 0; //Address of the singleton
-
-
}
-
-
SysParms::SysParms()
-
{
-
-
}
-
SysParms::~SysParms()
-
{
-
delete instance;
-
instance = 0;
-
}
-
-
//The "official" access point
-
SysParms* SysParms::Instance()
-
{
-
//"Lazy" initialization. Singleton not created until it's needed
-
if (!instance)
-
{
-
instance = new SysParms;
-
}
-
return instance;
-
}
-
void SysParms::MaxWidth(std::streamsize arg)
-
{
-
this->maxwidth = arg;
-
}
-
streamsize SysParms::GetMaxWidth()
-
{
-
return this->maxwidth;
-
}
-
-
ostream& operator<<(ostream& os, const string& str)
-
{
-
streamsize max = SysParms::Instance()->GetMaxWidth();
-
streamsize length = str.size();
-
-
for (int i = 0; (i < max) && ( i < length); ++i)
-
{
-
os << str[i];
-
}
-
return os;
-
}
-
-
int main()
-
{
-
-
string str("abcdefghijklmnop");
-
SysParms::Instance()->MaxWidth(10);
-
cout << str << endl;
-
SysParms::Instance()->MaxWidth(5);
-
cout << str << endl;
-
-
return 0;
-
}
-
-