Aashish Jha
Aashish Jha

Reputation: 17

If i want to give any input to my function using cout... how can I give

int do_something(int num)
{
    //stuff happens.
}

do_something(5)

Here we have given the input directly to the parameter, but if I want to give input to this using cout...

Like It asks me to give input and it directly store in the (int num).... How can I give... Please suggest me

Upvotes: 0

Views: 732

Answers (3)

Sajib
Sajib

Reputation: 414

cout is an output stream. It is not to take input from. You can use cin (which is an inputs stream) to take the input and then pass it to your function.

int n;
std::cin >> n;
do_something(n);

Upvotes: 0

Rohan Bari
Rohan Bari

Reputation: 7726

The cout object in C++ is an object of class ostream. It is used to display the output to the standard output device i.e. monitor. It is associated with the standard C output stream stdout.

Hence, you can't use cout to accept input values. Rather, the possible way is just cin simply.

Consider the example:

int do_something(int num) {
    .
    .
}

int param, result;

std::cout << "Enter something: ";
std::cin >> param;

result = do_something(param); // return type is integer

This is the right method.

Upvotes: 2

Derek C.
Derek C.

Reputation: 998

int x;
std::cin >> x;
do_something(x);

Very simply that would work. This pulls a value from std::cin and puts it into the variable x.

There is a problem with this, the user can put whatever value they want into this. If you expect that the input will ALWAYS be an int don't worry.
Likely you'll need to look into verifying inputs. Here is a SO question about that topic.

Upvotes: 1

Related Questions