1

learning c++ and can't understand why I can't use "std::cin" as an argument.

#include <iostream>
#include "stdafx.h"
int doubleNumber(int a)
{
    return 2 * a;
}

int main()
{
    int x;
    std::cout << doubleNumber(std::cin >> x);
    return 0;
}

3 Answers3

3

std::cin >> x returns a reference to cin, which isn't implicitly convertible to int.

You can use the , operator like so:

(std::cin >> x, x)

to first run std::cin >> x and then evaluate that expression to x.

#include <iostream>
int doubleNumber(int a)
{
    return 2 * a;
}

int main()
{
    int x;
    std::cout << doubleNumber( (std::cin >> x, x) );
    return 0;
}

Splitting it will probably into two lines will probably make it more readable, though.

In any case std::cin >> x can be used as an expression. E.g., it's common to have streams implicitly converted to booleans to check whether they're in a succeeding (good) state. (E.g., if(std::cin >> x){ //...)

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
2

You presumably want to pass x. But the result of cin >> x is cin, not x.

The solution is easy

 std::cin >> x;
 std::cout << doubleNumber(x);

You can't actually pass cin if you did want to because it's a stream, not an int.

And the return type of >> is the way it is in order to allow things like std::cin >> x >> y >> z; to work.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
1

std::cin is a global object and operator >>, which you are calling is a method that returns std::cin again, so you can write things like:

std::cin >> x >> y;

What I am trying to say is that the output of std::cin >> x is not the value you just typed in, as you seem to expect, but std::cin itself.

See http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt for further details.