0

I'm doing a relatively simple assignment asking us to intake integers and fail gracefully if it hits something that isn't an integer, written in C++. I'm fairly experienced with the language, and I knew it had functionality for checking reading errors in ios::failbit. As a result I'm using cin.fail() to check for errors here, but its running one loop too late--that is, its running the rest of the code first, and not realizing an error happened until the next time it checks the buffer. The obvious solution is to just check twice, but that just causes infinite loops (even if I flush or clear cin.) Is there any way to check more immediately?

Here's my code:

    int min = 101; //One higher than the max.
    int pile = 0;
    int count = 0;
    int temp = 0;
    int fail;
    std::cout << "Input a series of integers between 0 and 100. When you wish to"
    " exit, enter -1.\n";
    while (true){
      std::cin >> temp;
      if (std::cin.fail()){
        std::cout << "FAILURE: Bad input. It probably wasn't an integer.\n";
        std::cout << "Reading will stop.\n";
        break;
      }
      std::cout << "\nTemp is " << temp << "\n";
      if (temp > 100 || temp == -1){
        break;
      }
      if (temp < min){
        min = temp;
      }
      pile += temp;
      std::cout << "Pile is " << pile << "\n";
      count++;
      std::cout << "Count " << count << "\n";
    }
    std::cout << "Your average was: " << (double)pile/count << ".\n";
    std::cout << "Your minimum was: " << min << ".\n";
    return 0;
}
  • Can minimize the reproduction? https://stackoverflow.com/q/17928865/2864740 – user2864740 Oct 03 '20 at 20:18
  • What input do you provide, what output does the program produce, and why do you believe this output is incorrect? – Igor Tandetnik Oct 03 '20 at 22:27
  • @IgorTandetnik inputting 2, 2, 2, and 2.5 adds the 2.5 into the average and then fails afterwards. Its running a loop too late, it shouldn't add in the 2.5. – lunchboxninja Oct 04 '20 at 19:27
  • When you type in `2.5`, `cin >> temp` reads `2` as an integer, and stops at the period since it's not part of a valid integer. Next time round, it starts reading with a period and fails since no character can be consumed as an integer. In other words, your input is not 2, 2, 2, and 2.5; it's 2, 2, 2, 2 and `.5` – Igor Tandetnik Oct 04 '20 at 19:29

0 Answers0