Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing input as a function argument using cin

My program:

class test
{
    int k;
    public:
    void changeval(int i){k=i;}
};
int main()
{   
    test obj; 
    int i;
    cin>>i;
    obj.changeval(i);
    return 0;
}

Is there any way, by which i can directly pass input from the user as an argument to the function changeval(int), without even initializing value to i??

I mean, i don't want to declare a variable just to pass value to a function. Is there any way i can avoid it? If yes, can I use it for constructors also? Thanks.

like image 203
Nikhil Gupta Avatar asked Jan 04 '14 19:01

Nikhil Gupta


People also ask

Can you Cin into a function?

The ability to define inputs as member functions allows you to use cin. get and cin. getline to treat user input as parts of a function. This is a simple and straightforward way to get input from a user and then manipulate it through programming.

How are function arguments passed?

Arguments are passed by value; that is, when a function is called, the parameter receives a copy of the argument's value, not its address. This rule applies to all scalar values, structures, and unions passed as arguments. Modifying a parameter does not modify the corresponding argument passed by the function call.

Can we use CIN for char?

The "c" in C++ cin refers to "character" and "in" means "input". Thus, cin means "character input".

What is CIN in CPP?

The cin object in C++ is an object of class iostream. It is used to accept the input from the standard input device i.e. keyboard. It is associated with the standard C input stream stdin. The extraction operator(>>) is used along with the object cin for reading inputs.


1 Answers

Nope. Now, you could put this into a function:

int readInt(std::istream& stream)
{
    int i;
    stream >> i; // Cross your fingers this doesn't fail
    return i;
}

// Then in your code:
obj.changeval(readInt(std::cin));

But of course, this still creates an int (it just moves it to the readInt function).

In reality, you have to create some object/memory space for the int to live in, so you can read it and pass it. Where you do this can be changed. But to simply answer your question: no.

like image 52
Cornstalks Avatar answered Sep 28 '22 07:09

Cornstalks