I want to pass user input directly to function without variable. Now I am doing this:
int temp, len;
cin >> len;
for (int i = 0; i < len; i++){
cin >> temp;
foo(temp);
}
Can I do it without temp? Maybe I should not use "cin"?
But in general no, there is no way to use cin without variables since the compiler needs to know the type of the object you are trying to read, and it gets that from the type of the variable.
getline for user input. The only time you would want to use CIN. get is when you want the include terminating characters, or if you want to use a more specific means to identifying what part of the user's input the program will use. For instance, if you define a member function using char line[25] and then use cin.
Every time you read from cin to a variable, the old contents of that variable is overwritten.
cin will stop its extraction when it encounters a blank space.
But in general no, there is no way to use cin without variables since the compiler needs to know the type of the object you are trying to read, and it gets that from the type of the variable. You can easily define a wrapper function to do this. template<class T> T get (std::istream& is) { T result; is >> result; return result; }
A function in C can be called either with arguments or without arguments. These function may or may not return values to the calling functions. All C functions can be called either with arguments or without arguments in a C program. Also, they may or may not return any values.
Function with arguments but no return value : When a function has arguments, it receive any data from the calling function but it returns no values. Syntax : Function declaration : void function ( int ); Function call : function( x ); Function definition: void function( int x ) { statements; }
Using , we can denote any function without using variables. We will follow two rules: If is a binary operation and and are functions, then is a function defined by In particular, means and . Also, for the operation of exponentiation, we let denote the function If and are functions, then the composition of and , i.e. , may be denoted .
You can still create wrapper function:
template <typename T>
T get_input(std::istream& cin)
{
T res;
std::cin >> res;
return res;
}
And then:
const int len = get_input<int>(std::cin);
for (int i = 0; i < len; i++) {
foo(get_input<int>(std::cin));
}
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