问题
More of a curiosity question than anything else, but is it actually possible to pass whatever goes through cin
to a function without having to waste a variable?
回答1:
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.
回答2:
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/
回答3:
The answer to your question is negative. In order to input something through a stream, you will have to "waste" a variable. You cannot pass the input data directly to a function without an intermediate variable.
回答4:
Sure:
f(*std::istream_iterator<T>(std::cin));
That’s probably not simpler than using a variable, though, and is undefined behavior if the stream fails to provide a T
.
来源:https://stackoverflow.com/questions/13028702/directly-capturing-cin-without-a-variable-c