473,387 Members | 1,624 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Need manipulator to set maximum I/O width

Johanus Dagius
I've written a lot of C programs but only a few in C++. In C you can set both the minimum and maximum width of a formatted I/O output by using standard printf() formats. For example, if I have a very large string and I only want to print out the first 10 chars I can do this in C:
Expand|Select|Wrap|Line Numbers
  1. printf("s=%.10s\n", very_long_string).
How do I do this with C++ manipulators? I've tried std::setw(width), but it seems to control only the *minimum* width, not the max. I'm looking for something like in C++:

Expand|Select|Wrap|Line Numbers
  1. std::cout << std::maxw(10) << very_long_string << std:endl;
I know there are many "work-arounds" such as using substr(), but that only works with std::string. I often work with plain old c-strings.

I've been told that manipulators can mimic anything that printf() does, but it seems they can't even constrain fields to some specified size! Correct me if I'm wrong.

Tnx, Johanus
Jun 22 '07 #1
4 5643
weaknessforcats
9,208 Expert Mod 8TB
Then write your own manipulator. Like endl. It's just a function with this prototype:
Expand|Select|Wrap|Line Numbers
  1. ostream& MyFunction(ostream&);
  2.  
For example suppose you want five asterisks to appear:
Expand|Select|Wrap|Line Numbers
  1. ostream& FiveStars(ostream& arg)
  2. {
  3.     arg << "*****";
  4.     return arg;
  5. }
  6.  
Then you call it by address:

Expand|Select|Wrap|Line Numbers
  1. cout << FiveStars << " Important! " << FiveStars << endl;
  2.  
The ostream::operator<<(ostream&, ostream& (*fp)(ostream&) ) just calls the function by address passing in the ostream itself as the argument.

Now you can do anything you want.
Jun 22 '07 #2
>>> Then write your own manipulator ...
OK, I understand your simple manipulator, which merely inserts and returns its own stuff into the output stream.

But I don't see how it can truncate output(s) further down the stream. I suspect this is not trivial thing to do. Would appreciate if someone could give me some pointers on how to do this (or even better: write the maxw(n) code for me :-)

I must say that I am surprised that something like maxw(n) is not part of "std"

Tnx,
Johanus
Jun 23 '07 #3
weaknessforcats
9,208 Expert Mod 8TB
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.

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class SysParms
  5. {   
  6.    private:
  7.         streamsize maxwidth;
  8.         SysParms(const SysParms&);  //Prevents making a copy
  9.  
  10.    protected:
  11.         SysParms();       //Only a SysParms member can call this
  12.                      //Prevents a user from creating singleton objects
  13.         virtual ~SysParms();  //Prevents just anyone from deleting the singleton
  14.  
  15.    public:
  16.  
  17.  
  18.        //The "official" access point.
  19.        static SysParms* Instance();
  20.        void MaxWidth(streamsize arg);
  21.        streamsize GetMaxWidth();
  22.  
  23. };
  24.  
  25.  
  26. namespace
  27. {
  28.     SysParms* instance = 0;        //Address of the singleton
  29.  
  30. }
  31.  
  32. SysParms::SysParms()
  33. {
  34.  
  35. }
  36. SysParms::~SysParms()
  37. {
  38.     delete instance;
  39.               instance = 0;
  40. }
  41.  
  42. //The "official" access point
  43. SysParms* SysParms::Instance()
  44. {
  45.    //"Lazy" initialization. Singleton not created until it's needed
  46.    if (!instance)
  47.    {
  48.       instance = new SysParms;
  49.    }
  50.    return instance;
  51. }
  52. void SysParms::MaxWidth(std::streamsize arg)
  53. {
  54.     this->maxwidth = arg;
  55. }
  56. streamsize SysParms::GetMaxWidth()
  57. {
  58.     return this->maxwidth;
  59. }    
  60.  
  61. ostream& operator<<(ostream& os, const string& str)
  62. {
  63.    streamsize max = SysParms::Instance()->GetMaxWidth();
  64.    streamsize length = str.size();
  65.  
  66.    for (int i = 0; (i < max) && ( i < length); ++i)
  67.    {
  68.       os << str[i];
  69.    }
  70.    return os;
  71. }
  72.  
  73. int main()
  74. {
  75.  
  76.     string str("abcdefghijklmnop");
  77.     SysParms::Instance()->MaxWidth(10);
  78.     cout <<  str << endl;
  79.     SysParms::Instance()->MaxWidth(5);
  80.     cout <<  str << endl;
  81.  
  82.     return 0;
  83. }
  84.  
  85.  
Jun 24 '07 #4
weaknessforcats wrote:
>>> 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 ....

Hey, thanks for the partial solution. (It works!) I really appreciate your efforts here to help me, but I think I'll just use fprintf() in my C++ code to format my outputs. The fstream manipulators are just too clunky.

Thanks,
Johanus
Jun 27 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: abracad | last post by:
Is there a way to force a maximum width for an image, table or table cell? cheers
6
by: Henro V | last post by:
And if there is one, is there a way to make forms that are wider? For every day on the form (first field) it needs to be followed by 52(!) datefields. I've widened the form as far as I can but I...
10
by: fjleon | last post by:
Hi, i am stuck using older ASP and have to dinamically fill a converted-word file as a form. Letīs suppose a row on a table has the name of someone like in a declaration: <span>Some random...
3
by: mrpeter05 | last post by:
I can not find a way to measure the height of a string by setting a maximum width! I need the strings maximum width to be the width of the screen and want to use that to calculate the height. Is...
4
by: p.numminen | last post by:
Is it possible, with CSS, to determine a certain _maximum_ width for a text, paragraph, division, etc.?
2
by: RKSpangler | last post by:
Greetings: Is there any way to determine the maximum width of all data elements in a particular column in a table? Sorting a column won't do it, of course, since it will use a collating...
3
by: =?iso-8859-1?q?Jean-S=E9bastien?= | last post by:
hello, is it possible to resize an image with same proportion. having a maximum height and a maximum width. the solution should work on main browsers (do not use max-height and max-width). ...
0
by: Andyxis | last post by:
Hi guys, I had been working in vb's data report and had set it's orientation to landscape at run time. There's NO error with it. The problem is I can't extend the width property of the data...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.