C++ Beginner Infinite Loop When Input Wrong Data Type and Help Evaluate My Code

后端 未结 1 1120
广开言路
广开言路 2020-12-21 13:36

I have an assignment to create a menu-based program to calculate area of several shapes using user-defined function. My code creates an infinite loop when a user input a cha

相关标签:
1条回答
  • 2020-12-21 13:55

    With float r1; cin >> r1; and non-numeric input, there is nothing consumed from input. Repeating cin >> r1 results in an endless loop.

    What to do?

    1. Check whether cin >> r1 was successful: if (cin >> r1) { /* process r1 */ }
    2. If not successful, do something to consume wrong input: else { cin.clear(); cin.ignore(); }

    std::ios::clear()

    Sets the stream error state flags by assigning them the value of state. By default, assigns std::ios_base::goodbit which has the effect of clearing all error state flags.

    std::istream::ignore()

    Extracts and discards characters from the input stream until and including delim.

    Example:

    #include <iostream>
    #include <limits>
    
    int main()
    {
      double value = 0.0;
      for (;;) {
        std::cout << "Value: ";
        if (std::cin >> value) {
          break; // success -> bail out of loop
        } else {
          std::cerr << "Wrong input!\n";
          std::cin.clear(); // reset state
          std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // consume wrong input
        }
      }
      std::cout << "Value: " << value << '\n';
      return 0;
    }
    

    Output:

    Value: Hello
    Wrong input!
    Value: 1.23
    Value: 1.23
    

    Live Demo on coliru

    0 讨论(0)
提交回复
热议问题