简体   繁体   English

使用std :: istream运行功能

[英]Running function with std::istream

I am trying to input a value in my function, which looks like this: 我正在尝试在函数中输入一个值,如下所示:

int funkcija( std::istream & in ) {
    int value(0);
    in >> value;
    if(not in) throw std::exception();
    if( value%2 == 0 ) {
        return (value/2);
    }
    else return (value*3)+1;
}

When I try to run it: 当我尝试运行它时:

int i(0);
std::cout << "Input a number: ";
std::cin >> i;
funkcija(i);

I get an error: ..\\working.cpp:17:14: error: invalid initialization of reference of type 'std::istream& {aka std::basic_istream&}' from expression of type 'int' ..\\working.cpp:7:5: error: in passing argument 1 of 'int funkcija(std::istream&)' 我收到一个错误:.. \\ working.cpp:17:14:错误:类型'int'.. \\ working.cpp类型的表达式对'std :: istream&{aka std :: basic_istream&}'引用的初始化无效:7:5:错误:传递'int funkcija(std :: istream&)'的参数1

What does it mean and how to solve it? 这是什么意思,以及如何解决? Thank you! 谢谢!

You are trying to pass the integer you've already read, try: 您正在尝试传递已经读取的整数,请尝试:

std::cout << "Input a number: ";
int i = funkcija(std::cin);
std::cout << i << " ";

While this would work it seems strange. 尽管这行得通,但似乎很奇怪。 Consider separating the input- and output-handling from the calculation to improve your design. 考虑将输入和输出处理与计算分开以改善设计。 Change the function to: 将该功能更改为:

int funkcija( int value ) {
   if( value%2 == 0 ) {
       return (value/2);
   }
   else return (value*3)+1;
}

and maybe call it like this: 也许这样称呼它:

std::cout << "Input a number: ";
int i;
if( !( std::cin >> i ) ) throw std::exception();
do {
    i = funkcija( i );
    std::cout << i << " ";
} while( i != 1 );

i is of type int not istreeam - you're passing i to the function, therefore its complaining that it's an int and not an istream. 我的类型是int而不是istreeam-您正在将i传递给函数,因此它抱怨它是int而不是istream。 You can probably pass in std::cin directly to the function. 您可能可以将std :: cin直接传递给该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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