-3

I want to know if a string contains a '1' or '0' so I wrote this code:

    if ((input.contains('0'))||(input.contains('1'))) {
        ui->answerbox->setText(QString::number(BinToDec(number)));
    }
    else {
        ui->answerbox->setText("Error");
    }

If I put in "014", it runs the if block but if I put "4" it runs the else block. What's wrong?

Tomaž
  • 59
  • 1
  • 2
  • 5
  • 5
    Nothing is wrong.The second string does not contain a `1` or a `0`, so it runs the else block. What were you expecting the code to do? – xEric_xD Dec 05 '17 at 08:53
  • What's the problem? "4" doesn't contain a 0 or a 1. – aatwo Dec 05 '17 at 08:54
  • Title says about numbers, but you check against '1' and '0' only. What exactly do you need? – vahancho Dec 05 '17 at 09:00
  • 1
    Are you mixing up the character '1' and '0' with binary representation of numbers? They are not the same. –  Dec 05 '17 at 09:02
  • If input is "4" the application must run the else block, as it does not contain 0 nor 1 – Ale Dec 05 '17 at 11:27
  • Oh I'm stupid. I expected it to run the if block if the string contains ONLY 1's or 0's and else block if it contains anything else than 1 or 0. – Tomaž Dec 05 '17 at 21:12

1 Answers1

1

Man this function BinToDec is a total disaster.

bool success;
auto value = input.toInt(&success, 2);
if (success) {
    ui->answerbox->setText(QString::number(value));
}
else {
    ui->answerbox->setText("Error");
}
Marek R
  • 32,568
  • 6
  • 55
  • 140