简体   繁体   中英

Why can't i use std:cin as an argument

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;
}

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. Eg, it's common to have streams implicitly converted to booleans to check whether they're in a succeeding (good) state. (Eg, if(std::cin >> x){ //... )

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM