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

爱⌒轻易说出口 提交于 2019-11-28 14:09:16

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/

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.

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.

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