2

Is there any way that I can continue input after end of file or invalid input. The record function will throw an exception if a certain data member is not recorded. I want to catch the exception and use another function rerecord to enter the information. The program will catch the exception and print the output but it won't do the last part.

int main()
{
    info person;
    try {
        person.record(std::cin);
    }
    catch(std::domain_error e) {
        std::cout << "Re-enter person info" << std::endl;
        person.rerecord(std::cin);
    }
}
Mars
  • 4,677
  • 8
  • 43
  • 65

1 Answers1

0

I think some input operation failed in person.record(std::cin); and cin is in a bad state. In this case "How do I flush the cin buffer?" should help. Especially, note the call to ignore(...) to get ride of the bad input!

Running code for demo:

#include <iostream>
#include <limits>

int main() {
    int i;

    std::cout << "Input: ";

    std::cin >> i;

    std::cout << "Received: " << i << "\nInput next:";

    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    std::cin >> i;

    std::cout << "Received: " << i << "\n";

    return 0;
}
Community
  • 1
  • 1
Tobias
  • 5,038
  • 1
  • 18
  • 39
  • If I hit Ctrl-D at the first input, std::cin.clear() does not remove EOF. If I repeat `std::cin.clear()` after ignore, EOF is actually removed from the flags, but cin doesn't input anything anymore. (g++ (Debian 10.2.1-6) 10.2.1 20210110) – Ale Mar 28 '22 at 17:45