cin 到没有变量的函数参数

Dim*_*tes 6 c++ input c++11

我想将用户输入直接传递给没有变量的函数。现在我这样做:

int temp, len;
cin >> len;
for (int i = 0; i < len; i++){
    cin >> temp;
    foo(temp);
}
Run Code Online (Sandbox Code Playgroud)

没有温度可以做吗?也许我不应该使用“cin”?

Jar*_*d42 4

您仍然可以创建包装函数:

template <typename T>
T get_input(std::istream& cin)
{
    T res;
    std::cin >> res;
    return res;
}
Run Code Online (Sandbox Code Playgroud)

进而:

const int len = get_input<int>(std::cin);
for (int i = 0; i < len; i++) {
    foo(get_input<int>(std::cin));
}
Run Code Online (Sandbox Code Playgroud)