Question

I'm trying to validate user input by using the QString::toDouble() function. The documentation says the function should be used like this:

double QString::toDouble ( bool * ok = 0 ) const;
/* 
   Returns the string converted to a double value.
   Returns 0.0 if the conversion fails.
   If a conversion error occurs, *ok is set to false; otherwise *ok is set to true.
*/

So I was trying to use the *ok to throw an error message if its false with the objective of only allowing users to enter valid integers or decimals. The problem is the message always returns valid even when words are entered. Here is my code so far:

void MainWindow::checkData()
{        
    bool validate;
    QString tempStr;
    tempStr = ui->lineEditValidate->text();
    double converted = tempStr.toDouble(&validate);
    if (validate = false)
    {
        QErrorMessage validateError;
        validateError.showMessage("Input is Invalid");
        validateError.exec();
    }
    else
    {
        QErrorMessage worksFine;
        worksFine.showMessage("valid");
        worksFine.exec();
    }
}

I have a feeling that I am not passing the validate argument properly but the documentation isn't solid enough for me to really know; maybe the QString::toDouble() function is converting letters into values.

Could someone explain where I've gone wrong?

Was it helpful?

Solution

if (validate = false)
         //  ^ problem! this is an assignment

With that, you're setting validate to false systematically, and testing the result of that assignment - which is false too.

This is incorrect. You need:

if (validate == true) {
        //   ^^ comparison here
  // conversion worked
} else {
  // conversion failed
}

It is even more usual to omit the comparison for boolean tests:

if (valid) { // do stuff if valid ...

Or:

if (!valid) { // do stuff if not valid ...

Your variable would be better named valid, or conversionOk or something like that. It's not an action, and it doesn't indicate whether something needs validation, but the result of that action/validation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top