Thread: What happens if...?

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    The larch
    Join Date
    May 2006
    Posts
    3,573
    That's because std::cin does input validation. You'll need to check the result of an input operation, and if there was a problem "ignore" unread characters and "clear" the error bits.

    Code:
    #include <iostream>
    #include <limits>
    
    int main()
    {
        int n = 1;
        do {
            if (std::cin >> n) {
                std::cout << "Ok " << n << '\n';
            }
            else {
                std::cout << "Not Ok\n";
                std::cin.clear();
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            }
        } while (n);
    }
    Last edited by anon; 12-21-2009 at 02:17 AM.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed