Tricky While loop problem

I have a Quadratic Equation program that recieves input from the user, and I only want the input to be numbers. I have this for my input function:


void getInput (double array[])
{
cout << "To use the 'Quadratic Formula' calculator," << endl
<< "please enter the values of a, b and c." << endl;

cout << "a: ";
cin >> array[0];
while (array[0] == 0 )
{
cout << '\a';
cout << "Not possible to divide by 0, see equation." << endl;
cout << "Enter a again: ";
cin >> array[0];
}

cout << "b: ";
cin >> array[1];

cout << "c: ";
cin >> array[2];

}

I can use the while loop to make sure a is not 0, but can I make a while loop so that a, b and c can't be a character? Otherwise it screws everything up and I get 1e9252 or something CRAZY!
Last edited on
Okay so I tried to follow your advice, but now I am getting really screwed with the while loops. I want there to be two conditions: If user inputs a zero display "can't divide by zero", or if user enters a letter display "ERROR". I don't know what is really going on, I am lost.



while (true)
{
getline(cin, input);


while (array[0] == 0 )
{
stringstream myStream(input);
cout << "Not possible to divide by 0, see equation." << endl;
cout << "Enter a again: ";
}
stringstream myStream(input);
if (myStream >> array[1])
break;
cout << "Invalid number, please try again" << endl;
This should work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
while ( true )
{
    getline ( cin, input );

    stringstream myStream( input );
    
    if ( myStream >> array[0] ) // check whether input was successful
    {
          if ( array[0] ) // check array[0] != 0
              break; // exit from while

          cout << "can't divide by zero";
    }
    else
         cout << "ERROR"; // not a number -input failed-
}
Works GREAT! Thanks a million!
Topic archived. No new replies allowed.