Cin Stream Error States - C++ File Stream

C++ examples for File Stream:cin

Description

Cin Stream Error States

Demo Code

#include <iostream>
#include <iomanip>
int main(int argc, const char *argv[]) {
    int integerValue;

    // display results of cin functions
    std::cout << "Before a bad input operation:"
              << "\ncin.rdstate(): " << std::cin.rdstate()
              << "\n    cin.eof(): " << std::cin.eof()
              << "\n   cin.fail(): " << std::cin.fail()
              << "\n    cin.bad(): " << std::cin.bad()
              << "\n   cin.good(): " << std::cin.good()
              << "\n\nExpects an integer, but enter a character: ";

    std::cin >> integerValue;//from  w  w  w. jav  a2  s.  c o m
    std::cout << std::endl;

    // display results of cin functions after bad input
    std::cout << "After a bad input operation:"
              << "\ncin.rdstate(): " << std::cin.rdstate()
              << "\n    cin.eof(): " << std::cin.eof()
              << "\n   cin.fail(): " << std::cin.fail()
              << "\n    cin.bad(): " << std::cin.bad()
              << "\n   cin.good(): " << std::cin.good() << std::endl
              << std::endl;

    std::cin.clear();

    // display results of cin function after clearing cin
    std::cout << "After cin.clear()"
              << "\ncin.fail(): " << std::cin.fail()
              << "\ncin.good(): " << std::cin.good() << std::endl;

    return 0;
}

Result


Related Tutorials