General Stream Manipulation in C++ - Closing Thoughts
(Page 4 of 4 )
Up to this point I have given you examples of the output part, so I have decided to leave this last section to the input part. One of the most interesting manipulators in the previous section is the black sheep setw.
This also works for the cin, as it is a member of the ios_base. However, there is a similar function that will do the same thing—let’s me introduce it now.
The insertion operator is no longer valid for a pure ifstream function, so we must call it explicitly or via the insertion operator, as I will present it in the instance below:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
istream::fmtflags oldflag = cin.flags();
ostream::fmtflags ooldflag = cout.flags();
string text;
//char text[10];
cout << setfill(')');
cout << " enter something: ";
cin.width(4);
while ( cin >> text)
{
cin.width(3);
cout.width(4);
cout << text << endl;
}
cin.flags(oldflag);
cout.flags(ooldflag);
return 0;
}
enter something: I am writing some code
)))I
))am
)wri
))ti
))ng
)som
)))e
)cod
)))e
Now there is an interesting way to format your code, or simply split it up into smaller inputs. The width function acts just like the setw, and it only works for the next input/output.
Additionally, if you are bored with being interrupted by the white spaces to read in a long line, you can decide to overwrite the white space skip. This way, you can read the text char-by-char, or read it all at once. The manipulator you need to use is skipws:
cin >> skipws; // skip the white spaces and look at them //as delimitations
cin >> noskipws; //return to default
With this we have covered all that is to be found within the manipulators already included in the STL. In future articles we will look at the low-level sequence reading of files, but before that we'll finish our work here with Custom Stream Manipulating in C++, so look for it.
Thank you for reading my article. I invite you to ask any question you might have here on the blog below or to join our friendly, ever-growing forum over at DevHardware and present your question there. Until the next time we meet, remember to “Live with Passion!”
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |