I can't seem to terminate this program with char 'q'. I have no problems with the program being modified to terminate by an int.
As it is now, the program will turn into an infinite loop when "q" is used.
I'm sure it has something to do with my initialization, but I can't see it (or lack the knowledge)
Your problem is that the variable a is a double.
I suggest setting char q = '\0' or to something other than 'q'. Then move the start of your while loop to before the cin >> a.
It will look something like this:
1 2 3 4 5 6 7 8
while( q != SENTINEL )
{
cin >> a;
/* Quadratic Stuff */
cout << "Enter \'q\' to quit or any other character to continue: ";
cin >> q;
}
A do-while loop would be better in this situation but you can do what you want.
Seriously I had a dumb moment, not being able to compare char to a double makes perfect sense.
However, I taking a a first year class, and I'm limited in my libraries. I have read a lot about using string to handle this problem, but I won't work for me.
"A do-while loop would be better in this situation but you can do what you want. "
I agree, but I have to have a terminate command from the start
#include <iostream>
#include <cmath>
#include <math.h>
#include <iomanip>
usingnamespace std;
char q = '\0' ;
constchar SENTINEL = 'q' ;
int main ()
{
double x1, x2, a, b, c ;
cout << "This program will solve for the Quadratic Formula\n";
cout << "Would you like to continue? (q to quit, any other key continues)\n";
cin >> q;
while( q != SENTINEL )
{
cout << "Input values as a, b, and c\n" ;
cout << "a = " ;
cin >> a ;
cout << "b = " ;
cin >> b ;
cout << "c = " ;
cin >> c ;
if (a > 0 && ((b * b - 4 * a * c) > 0))
{
x1 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a) ;
x2 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a) ;
cout << " The roots are " << x1 << "and " << x2<< endl;
}
elseif ( a == 0)
{
cout << "Zero divide" << endl;
}
else
{
cout << "No real roots" << endl;
}
cout << "Enter \'q\' to quit or any other character to continue: ";
cin >> q;
}
system ("PAUSE");
return (0);
}
I have read a lot about using string to handle this problem, but I won't work for me.
Using strings to validate input is a really good thing, try this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
string inpt;
while(true)
{
cout << "Input values as a, b, and c; or q to quit \n" ;
cout << "a = " ;
cin >> inpt;
if ( inpt[0]=='q' ) break;//exit from the loop
//The loop is continuing so you don't need the else
stringstream ss(inpt);
ss >> a; // if the 1st character wasn't 'q' set the contents of the input to a
//...
}
( You should do even more input validation than this )