Using streams in C++ is an easy and intuitive task. However, sometimes you may want to customize the input/output on a deeper level. This is possible in a powerful and easy way with the use of the manipulators.
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:
using namespace std;
istream::fmtflags oldflag = cin.flags();
ostream::fmtflags ooldflag = cout.flags();
cout << setfill(')');
cout << " enter something: ";
while ( cin >> text)
cout << text << endl;
enter something: I am writing some code
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++, solook 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.