0

So I'm trying to get my Quadratic equation solution code to loop unless "0" is entered as any 1 of the quadratic coefficients. It works fine up until entering a non integer value, in which the program terminates. I'd like the code to spit out a message prompting the user to enter a numerical value, and continue the loop as normal.

#include <iostream>

#include <cmath>

using namespace std;

int main() {
for ( ; ; ){
float a, b, c, D, x1, x2, real, im;
cout << "Please enter the Quadratic Coefficients" << endl;
cin >> a >> b >> c;
if (cin.fail()){
    cout << "Error, please enter numerical values!" << endl;
    cin >> a >> b >> c;
}
if ((a == 0) || (b == 0) || (c == 0)){
    break;
}
D = b*b - 4*a*c;
if (D < 0) {
    real = -b/(2*a); 
    im = sqrt(-D)/(2*a);
    cout << "Roots are Complex" << endl;
    cout << "x1 = " << real << "+" << im << "i" << endl;
    cout << "x2 = " << real << "-" << im << "i" << endl;

      }
else if (D == 0) {
x1 = (-b + sqrt(D)) / (2*a);
cout << "Real and Repeated Roots" << endl;      
cout << "x1 = " << x1 << endl;
   }
 else if (D > 0) 
{   
  x1 = (-b + sqrt(D)) / (2*a);

  x2 = (-b - sqrt(D)) / (2*a);

cout << "Real and Distinct Roots" << endl;
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
} } 

  return 0; 
    }
Nick Chr
  • 3
  • 3
  • If there's a mismatch between the expected and actual input, then the `operator>>` function will stop immediately, and the non-matching input will not be extracted from the input buffer. I suggest you [read a whole line](http://en.cppreference.com/w/cpp/string/basic_string/getline) and attempt to parse the input separately (perhaps with the help of e.g. [`std::istringstream`](http://en.cppreference.com/w/cpp/io/basic_istringstream)). – Some programmer dude May 29 '18 at 16:31
  • I'm confused as to what does not work. I can run it without any problem, including non-integer inputs like 1.0, 2.5 0.1, or mixed ones like 1, 2.5, 0.1. What inputs exactly don't work for you? Edit: nevermind, you mean non-numerical input, I see it now – GeckoGeorge May 29 '18 at 16:42
  • if ((a == 0) || (b == 0) || (c == 0)){ break; => you miss some valid solutions here – skeller May 29 '18 at 19:39
  • @GeckoGeorge My bad, I meant non-numerical which of course is also non integer :) – Nick Chr May 30 '18 at 07:24
  • @skeller You're correct, I should have replaced it with if ((a == 0)) { break; } – Nick Chr May 30 '18 at 07:24

1 Answers1

0

This solution here should help.

cin.fail() set the input stream into a failed state, and you need to reset it manually to get it to do any further work. When you call cin again, it will notice its failed state and just go on, otherwise.

cin >> a >> b >> c;
if (cin.fail()){
  cin.clear(); //removes error flags
  cin.ignore(); //ignores last input
  cout << "Error, please enter numerical values!" << endl;
  cin >> a >> b >> c;
}
GeckoGeorge
  • 446
  • 1
  • 3
  • 11