学习c++,不明白为什么我不能使用“std::cin”作为参数。
#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
返回对 cin
的引用,它不能隐式转换为 int
。
您可以像这样使用 ,
运算符:
(std::cin >> x, x)
首先运行 std::cin >> x
,然后将该表达式计算为 x
。
#include <iostream>
int doubleNumber(int a)
{
return 2 * a;
}
int main()
{
int x;
std::cout << doubleNumber( (std::cin >> x, x) );
return 0;
}
不过,将它分成两行可能会使它更具可读性。
在任何情况下,std::cin >> x
都可以用作表达式。
例如,将流隐式转换为 bool 值以检查它们是否处于成功(良好)状态是很常见的。 (例如,if(std::cin >> x){//...
)
关于c++ - 为什么我不能使用 std :cin as an argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37368640/