More of a curiosity question than anything else,
but is it actually possible to pass whatever goes
through std::cin
to a function as a parameter without
defining an temporary variable just for reading from input?
Instead of using an extra temporary variable:
#include <iostream>
using namespace std;
string time; // extra define temporary variable for input
// now 2 lines follow with separate operations
cin >> time; // 1) input to "time"
in_time = get_minutes (time); // 2) put "time" to function as parameter
cin >> time; // another extra line
wake_up = get_minutes (time);
cin >> time; // and another other extra line ....
opens = get_minutes (time);
I want to directly use std::cin
in a function parameter:
#include <iostream>
using namespace std;
in_time = get_minutes (<use of cin here>);
wake_up = get_minutes (<use of cin here>);
opens = get_minutes (<use of cin here>);
Is this possible?
You can easily define a wrapper function to do this.
template<class T>
T get(std::istream& is){
T result;
is >> result;
return result;
}
Any decent compiler will use NRVO to eliminate the copy.
You can use it like this
f(get<int>(std::cin));
Make sure not to use it multiple times in one statement though. The order of the stream operations is unspecified if you do something like this.
f(get<int>(std::cin),get<int>(std::cin));
You could get the two ints in either order.
cin
is just a stream, it doesn't have any magic. You can use the other stream methods to do whatever you want.
Check out http://www.cplusplus.com/reference/iostream/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With