aks
aks

Reputation: 526

How to pass cin to a function?

I am learning about different stream state flags/functions in C++ such as good(), goodbit, bad(), badbit and so on. While testing with std::cin, I am unable to pass cin as an argument to a function (the compiler shows a lot of errors)

#include <iostream>
#include <sstream>

 void print_state (const std::istream& stream) {
    std::cout << " good()=" << stream.good();
    std::cout << " eof()=" << stream.eof();
    std::cout << " fail()=" << stream.fail();
    std::cout << " bad()=" << stream.bad();
} 

int main() {
    std::cin.clear (std::ios::goodbit);
    std::cout << "goodbit: " << print_state(std::cin) << std::endl;

    std::cin.clear (std::ios::eofbit);
    std::cout << "eofbit: " << print_state(std::cin) << std::endl;

    std::cin.clear (std::ios::failbit);
    std::cout << "failbit: " << print_state(std::cin) << std::endl;

    std::cin.clear (std::ios::badbit);
    std::cout << "badbit: " << print_state(std::cin) << std::endl;

    return 0;
}

Desired output:

goodbit: good()=1 eof()=0 fail()=0 bad()=0
 eofbit: good()=0 eof()=1 fail()=0 bad()=0
failbit: good()=0 eof()=0 fail()=1 bad()=0
 badbit: good()=0 eof()=0 fail()=1 bad()=1

I know I can call the function directly with cin, such as std::cin.good(), but I want to know how can I pass cin as an argument to a function.

Edit: I get a LOT of errors during compilation. An example:

F:\cpp_programming\stream_states.cpp: In function 'int main()':
F:\cpp_programming\stream_states.cpp:13:27: error: no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'void')
  std::cout << "goodbit: " << print_state(std::cin) << std::endl;
  ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~

Upvotes: 1

Views: 9437

Answers (1)

aks
aks

Reputation: 526

Since print_state does not return a value, it cannot be used with the insertion operator <<. The simplest way to correct this, is to call print_state on its own.

print_state(std::cin);

The corrected code is given below:

#include <iostream>
#include <sstream>

 void print_state (const std::istream& stream) {
    std::cout << " good()=" << stream.good();
    std::cout << " eof()=" << stream.eof();
    std::cout << " fail()=" << stream.fail();
    std::cout << " bad()=" << stream.bad();
} 

int main() {
    std::cin.clear (std::ios::goodbit);
    std::cout << "goodbit: "; print_state(std::cin); std::cout << std::endl;

    std::cin.clear (std::ios::eofbit);
    std::cout << "eofbit: "; print_state(std::cin); std::cout << std::endl;

    std::cin.clear (std::ios::failbit);
    std::cout << "failbit: "; print_state(std::cin); std::cout<< std::endl;

    std::cin.clear (std::ios::badbit);
    std::cout << "badbit: "; print_state(std::cin); std::cout << std::endl;

    return 0;
}

To answer my own question

cin can be passed to a function as a function argument, such as:

functionName(std::cin);

Upvotes: 7

Related Questions