Search code examples
c++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&)'

What does it mean and how to solve it? Thank you!


Solution

  • 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 );