0
Increment subsequent output.
Is there a way to increment every subsequent output of h, without calling the function m(h) every time before outputting h? (I.e, calling m(h) once and every other cout << h; increasing by 1. https://code.sololearn.com/c68I5rc15z82/?ref=app
6 Respostas
+ 1
You can just write this:
cout << h++ << endl;
That will print h and increase it by 1
+ 1
I think that is not possible. At least not easily. The main problem is that h is of integral type int which means it only stores the content (a number) of the variable. So how should those calls to cout << h know that you want the function m to be called on h. For this to work you would have to change how cout outputs data for an integral type which is at least complicated. The only other way I can think of how this could be done is to define a custom type (class or struct) and overload the operator<< for output streams. Then you can call any arbitrary function on the variable before it is printed. But that comes at the cost of wrapping a single int value inside a custom type which is probably not really worth it.
I made a code which shows how that could be done but this is still not really the exact behavior you wanted because that would be even more complicated (you would have to store which function to call and so on)
https://code.sololearn.com/cA24A3A13a25/?ref=app
0
Hape thanks, but this wasn't what I meant. Doing this, I wouldn't need to call the function m();.
0
I am not quite sure what exactly you are trying to do. But if you want to call the function m you can of course also write this:
cout << m(h) << endl;
0
Hape it should be like
int main (){
int h=5;
m(h);
cout << h; // output: 6;
cout << h; //output: 7;
cout << h; //output: 8;
}
// By calling m(h) just once in the main function.
0
Hape thanks very much for the help.