Directly capturing cin without a variable - C++ [closed]

好久不见. 提交于 2019-11-27 08:13:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!