Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

cin

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?

like image 296
user1749737 Avatar asked Jan 16 '23 06:01

user1749737


2 Answers

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.

like image 188
Dirk Holsopple Avatar answered Jan 28 '23 16:01

Dirk Holsopple


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/

like image 29
Daniel Dinu Avatar answered Jan 28 '23 15:01

Daniel Dinu