/* ** $Id: sum.cc 824 2008-03-09 19:23:52Z phf $ ** ** Silly example for summing a sequence of positive integers ** from standard input. ** ** Also shows pieces of the error handling protocol that can ** be used with the std::cin stream. */ #include #include // just to illustrate how the status changes... void print_state() { std::cout << "std::cin status: "; if (std::cin.eof()) { std::cout << "[EOF]"; } if (std::cin.good()) { std::cout << "[GOOD]"; } if (std::cin.bad()) { std::cout << "[BAD]"; } if (std::cin.fail()) { std::cout << "[FAIL]"; } std::cout << std::endl; } // and here we go summing those positive integers... int main() { print_state(); int sum = 0; // can't use the usual while construct since we want // to skip input errors; if we use while (cin>>x) we // would not only stop the loop on EOF, but also on // other error conditions... :-/ for (;;) { int x; std::cin >> x; // read an integer print_state(); if (std::cin.eof()) { std::cout << "End of file, done!" << std::endl; break; } if (std::cin.good()) { if (x > 0) { sum += x; } else { std::cout << "Not a positive integer, done!" << std::endl; break; } } else { std::cout << "You didn't type an integer!" << std::endl; std::cin.clear(); std::string crap; std::cin >> crap; // skip whatever it was up to next whitespace } } std::cout << "The sum is " << sum << " I hope..." << std::endl; }