Could anyone explain me the declaration of the setw manipulator? I was completely blown off trying to understand it.! The declaration of the setw in iomanip is as follows
smanip setw(int)
now what is smanip? what happens when we give std::cout << setw(10) << "Hai" [ i want to know how the output is actually affected by setw, in other words the actions happening under the hood)
smanip is an implementation-defined type. The library can define or typedef it to anything it likes, as long as the job gets done.
In practice, it will be some kind of structure representing (a) the manipulation to be performed, and (b) the argument 10 to be used in this manipulation. It might also have a function to perform the manipulation, or it might not, depending how the implementation has defined operator<<(ostream &, smanip), or some similar overload to catch the necessary operand types. I haven't checked my implementation to find out.
As for how the output is affected: my_stream << setw(10) is defined to have the same effect on the stream as calling my_stream.width(10). So the operator<< overload will ensure that happens in some implementation-specific way. The operator overload for non-parameterized stream manipulators is defined specifically to call the manipulator, but with smanip there's a little more freedom for implementations.
setw(int) by itself doesn't modify anything. It simply returns a stream manipulator (smanip) that can be used to modify the stream's behaviour.
// setw example
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
cout << setw (10);
cout << 77 << endl;
return 0;
}
Related
Why does
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::fixed << std::setw(4) << std::setprecision(0);
std::cout << 4;
std::cout << 4;
}
print
" 44
(ignore the quote, it's just to get the formatting right)
and not
" 4 4
?
I thought that the iostream 'modifiers' persistent on the stream until they are explicitly changed/reset. I have a bunch of numbers I need to print with a certain prefix so that all fields have equal width; should I re-apply my modifiers every time I print one? Doesn't seem very efficient.
Unfortunately you've wandered into one of the areas of the standard that's a little archaic and seemingly without any overarching design goals.
This is undoubtedly historic as the iostreams library AFAIAA, was not originally part of the STL which is what became the standard library.
It's worth reading the notes on all std::ios_base members and the associated manipulators.
For example:
http://en.cppreference.com/w/cpp/io/ios_base/width
Some I/O functions call width(0) before returning, see std::setw (this results in this field having effect on the next I/O function only, and not on any subsequent I/O)
The exact effects this modifier has on the input and output vary between the individual I/O functions and are described at each operator<< and operator>> overload page individually.
Anticipating:
But that's just <insert expletive>!!!
A: yup.
I am relatively new to the C++ world.
I know std::cout is used for console output in C++. But consider the following code in C :
#include<stdio.h>
int main(){
double dNum=99.6678;
printf("%.02lf",dNum);
//output: 99.67
return 0;
}
How do I achieve the similar formatting of a double type value upto 2 decimal places using cout in C++ ?
I know C++ is backward compatible with C. But is there a printf() equivalent in C++ if so, then where is it defined ?
This is what you want:
std::cout << std::fixed << std::setprecision(2);
std::cout << dNum;
and don't forget to :
#include <iostream>
#include <iomanip>
There is no equivalent. It is a pain using cout for formatted output.
All suggested solutions calling setprecision and similar are awfull when using long formats.
boost::format does not support some very nice features. Incompatibilities with printf. I still use printf because it is unbeatable.
If you want to use printf like formatting you should probably use snprintf (or build an allocating variant of that on top of that). Note that sprintf requires you to be able to guarantee that the result will not overrun the buffer you have to keep defined behaviour. With snprintf on the other hand can guarantee that it will not overrun the buffer since you specifiy the maximal number of characters that will be written to the string (it will instead truncate the output).
You could even build something that can directly be fed to an ostream on top of snprintf by automatically allocate the buffer and place in an object that on destruction free that memory. This in addition with a method to feed the object to an ostream would finish it off. Something like (with room for improvements):
struct Format {
char buf[999];
Format(fmt, ...) {
va_list ap;
va_start(fmt, ap);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
}
}
ostream& operator<< (ostream& os, Format const& str);
then you use this as:
cout << Format("The answer is %d", 42) << endl;
If you're using the GNU libraries you could of course use printf directly since cout and stdout are the same object then. Otherwise you should probably avoid mixing stdio and iostreams as there is no guarantee that these are synchronized with each other.
If you really want to reuse the same formatting techniques as in C, you may use Boost::format, which does exactly that:
cout << boost::format("%.02lf") % dNum;
But is there a printf() equivalent in C++ if so, then where is it defined?
There is a standards proposal P0645 to add a similar formatting facility to C++. In the meantime you can use the {fmt} library that implements this proposal and more:
#include <fmt/core.h>
int main()
fmt::print("{:.02f}", 99.6678);
}
P0645 and {fmt} use Python-like format string syntax which is similar to printf's but uses {} as delimiters instead of %.
Also the type information is preserved so you don't need l or other noisy specifiers.
Save your program as CPP and run it.
It runs and prints the answer.
Because C++ also has the printf() and scanf() like C.
You can also use sprintf in C++ to 'print' into a string and then cout that string. This strategy leverages your experience with printf-style formatting.
To output a value to the console using C++, you need the global ostream object cout and the << operator. endl is another global ostream object used as line break.
All are defined in the <iostream> header file. You can also use various formatting flags to control the presentation of the output...
#include<iostream>
using namespace std;
int main() {
double dNum = 99.6678;
cout << dNum;
cout.setf(ios::scientific, ios::floatfield); // format into scientific notation
cout << dNum;
cout.precision(8); // change precision
cout << dNum;
system("pause");
return 0;
}
The functional equivalent of your printf() call, using std::cout, is
std::cout << fixed << setprecision(2) << dNum;
It is necessary to #include <iomanip> and <iostream>.
The printf() equivalent in C++ is std::printf(), declared in <cstdio>.
Also, thanks to backward compatibility to C - specifically C++98 was required to maximise backward compatiblility to C89 - C's printf() declared in <stdio.h> is also available in C++. Note, however, that <stdio.h> is deprecated (tagged for removal from a future version of the C++ standard). Also, not all features of printf() introduced in C99 (the 1999 C standard) or later are necessarily supported in C++.
I don't quite understand what this means...I'm just learning C++ from my very very very basic Python experience...and so this may be a very stupid question. My question is...say you have your classic "Hello World" program and you have the line:
cout<<"Hello World!"<<endl;
what does the << mean...because I was just looking at using input in C and saw that you'd do something like:
int i;
cin>>i;
and I noticed that it has >> instead of << and I've read that those are bitwise shifts...and I don't exactly understand what those are...but I think it might be different here...Help...Thanks in advance
In Python, you can implement __lshift__ and __rshift__ to do whatever you want. In C++, it is the same - while the classic meaning is bitwise shift right and bitwise shift left, you can make it do whatever you want.
This is probably one of the most blatant violations of "sensible" operator overloading in C++, but that is just how std::ostream and std::istream work. For all of the C++ lovers out there (myself included), I apologize for this strange choice of operators. Just think of it as the direction that the data flows in (cout << foo puts a foo in cout, cin >> foo puts cin in foo), smile and be happy. From a newcomer, it really doesn't make sense, but drink the C++ Kool Aid and you'll be OH YEAH about it. Trust me.
Operators can have different meanings when applied to different types, and C++ allows the developer to overload operators to do just that. It's a powerful technique that should be used cautiously, since it's really easy to make programs unreadable if you overload unjudiciously.
Therefore >> and << are bit shift operators when the left side is an integer, but input and output operators when the left side is an I/O stream or similar. Read them as arrows pointing which direction the data flows.
Originally, it did mean bitshift. And you can still use it as a bitshift for an int (or other basic type).
Classes let you redefine operators. This allows you to create iterators, for which ++ actually does what you want (iterates to the next element), by modifying an internal member appropriately.
<< and >> are also operators, which can be redefined for classes, and this allows them to be used as "stream insertion/extraction operators".
The ostream class actually defines ostream& operator<< (Type); and the istream class defines istream& operator>> (Type&);
You can see more details about i/ostream here: http://www.cplusplus.com/reference/iostream/
Full details of ostream's operator<< and of istream's operator>>.
You can even write your own such operators to be able to do cout << myclass;:
class MyClass{ ... };
ostream& operator<< (ostream& os, const MyClass& myclass) {
// code to insert it, usually something like:
return os << myClass.a << ' ' << myClass.b;
}
// and now you can do this:
MyClass m;
std::cout << m;
The << and >> operators are bitshift operators, but, for input/output streams, they are overloaded (=>their meaning is redefined) so that they are used to insert/extract stuff into the streams.
I think they were used because they look intuitive (they indicate the direction of the stream of data) and because they are almost never used for other purposes.
Instead of saying
print "Hello" + "world" #I know, you wouldn't actually do it like this.
where "print" is the command and "hello world" is your text,
c++ works as
cout << "Hello" << "World"; // or like this. But...
int i = 42;
cout << "The answer is: " << i; //you may want to do this
c++ uses "cout" as the command and "<<" as a joiner, or, more technically, an operator used on the out stream.
cin works similarly where the >> is just an operator that works on the in stream.
I'd like to provide an std::ostream that may or may not, from the user's point of view, encrypt its contents.
Imagine some random function that uses an std::ostream&:
void write_stuff( std::ostream& stream ) {
os << "stuff";
}
Whether stuff is output in cleartext or is encrypted is dependent on how the stream argument was initialized.
I'm thinking about inheriting from std::basic_streambuf, but I'm not sure it's the best way to go. I think the ideal scenario is some sort of filter object which is run before the contents are actually output. That way it'd be easy to chain operations, e.g. encrypting and then hex-encoding, which is a benefit that making my own basic_streambuf does not seem to give (not easily at least).
Any advices?
Thanks.
UPDATE: I followed the strategy laid out by the accepted answer. I found this article on writing a custom streambuf which performs XOR obfuscation to be extremely helpful as a starting point.
A streambuf can be implemented in terms of another arbitrary streambuf that's either passed in as an argument to the constructor or set with a special member function. And that allows you to stack streambuf implementations like you were thinking of.
You could even make a manipulator that uses the ostream's rdbuf function to get the current streambuf, call a function on your streambuf that sets the 'stacked' streambuf, and then calls rdbuf again to replace the ostream's streambuf with your own.
aes_ctr_streambuf encrypter(key);
zlib_streambuf compressor;
::std::cout << stack_streambuf(encrypter) << stack_streambuf(compressor);
It is hard to describe in short what you have to do in order to create an I/O stream for the new source or sink. Luckily, Jonathan Turkanis and CodeRage, LLC have created very nice building blocks with exceptional documentation that can help you save hundreds of hours of research and development of new streams. The library is called Boost.Iostreams.
The second example in documentation exactly shows how to solve your problem.
Also, note that they already have an output stream with zip compression. So maybe you don't even need to write a single line of code.
Good luck!
I'm not sure that what I'm about to suggest is exactly what you need (and its too complicated to be a comment), but have you ever heard of the stream manipulators ?
#include <iostream>
#include <iomanip>
int main(int, char**)
{
int a = 10;
std::cout << "a: " << a << std::endl; //outputs: "a: 10"
std::cout << "a: " << std::hex << a << std::endl; //outputs: "a: a"
std::cout << "a: " << std::dec << a << std::endl; //outputs: "a: 10"
return EXIT_SUCCESS;
}
You may indeed use a similar pattern (this matches what you actually call a "filter" object) to somehow change the state of your custom stream object.
i have an overloaded operator << trying to make it work like this
mystream<<hex<<10;
i have overloaded method
mytream& operator<<(ios_base& (*m) ios_base&)
This gets called whenever hex is encountered cause the parameter passed in the method is a function pointer of type same as hex or like some other output manipulators like dec, oct.
i have two problems
1) how do i retrieve the parameter the hex would be operating on, in this example 10
2) how do i know that the << operator is being called for hex and not other manipulator function like oct and dec
Thanks
1) hex is not operating on the parameter 10. << operators associate left-to-right, which means your code is the same as:
(mystream<<hex)<<10;
So your overload has to return an object which, when 10 is shifted into it, prints in hex (or if not prints, writes data somewhere). As everyone says, this is done by saving flags in the stream object itself, then returning *this. The reason flags are used is precisely because the "10" is not available yet, since the second << has not been evaluated yet. The first << operator call cannot print anything - it just has to get ready for when the second one is called.
2) hex is a function. It can be compared with other functions:
ostream &operator<<(ostream &s, ios_base& (*m)(ios_base &)) {
if (m == hex) {
} else if (m == oct) {
} else if (m == dec) {
}
}
Except you don't normally want to do that, you want the default behaviour, which is something like:
ostream &operator<<(ostream &s, ios_base& (*m)(ios_base &)) {
return m(s);
}
(I may be wrong on that, I've never looked at the implementation, but the general idea is that the operator calls the manipulator function, and the manipulator (the clue's in the name) manipulates the stream).
std::hex sets the std::ios::hex format flag on its parameter. Then in your operator<<(int) override, if you have one, check the format flags by calling flags().
3) Manipulators which take paramers are functions too, but their return types are unspecified, meaning it's up to the implementation. Looking at my gcc iomanip header, setw returns _Setw, setprecision returns _Setprecision, and so on. The Apache library does it differently, more like the no-args manipulators. The only thing you can portably do with parameterized manipulators is apply them to an iostream with operator<<, they have no defined member functions or operators of their own.
So just like hex, to handle setw you should inherit from std::ios_base, rely on the operator<< implementation provided by your library, then when you come to format your data, examine your own width, precision, etc, using the width(), precision(), etc, functions on ios_base.
That said, if for some bizarre reason you needed to intercept the standard operator<< for these manipulators, you could probably bodge something together, along these lines:
template <typename SManip>
mystream &operator<<(mystream &s, SManip m) {
stringstream ss;
// set the state of ss to match that of s
ss.width(s.width());
ss.precision(s.precision());
// etc
ss << m;
// set the state of s to match that of ss
s.width(ss.width());
s.precision(ss.precision());
// etc
return s;
}
I do consider this a bodge, though. You're not really supposed to interfere with stream manipulators, just let your base class do the work and look up the results.
When operator<< gets called with hex or oct or dec, set a flag in your mystream object. When operator<< is called with a number, check to see if any of these flags are set. If so, convert the number to hex/octal/decimal and display it.
In answer to your second question, the parameter m is a pointer to the manipulator function. You can check that it's not null, then call that function, passing *this. hex() is as simple as setting a flag in the passed stream object, as Zifre suggested. Then when processing the integer, check if the flag in the stream object is set, and output accordingly.
This is how the standard library implements its manipulator functions.
In your example, hex operates on (changes the state of) the stream, not the following parameters. hex has no notion of, or any relation to other << calls.
Looking at how other io manipulators are implemented would go a long way to clearing things up.
You should be manipulating ios_base::flags
http://www.cplusplus.com/reference/iostream/ios_base/flags/
which is what the standard hex does.