Question

I'm a beginner, made a function which takes input from lineedit converts it into a array and then searches it to find a word. If the word is found it prints successs in a label, otherwise prints error.Problem is that it every time prints error no matter what i enter. What am I doing wrong.

void MainWindow::on_consoleEdit_returnPressed()
{
    QString text = ui->consoleEdit->text();

    char enteredCmd[4096];
    strcpy(enteredCmd, "Some string data");
    text = enteredCmd;
    //enteredCmd contains all the data that text string contains
    char *open = strstr(enteredCmd, "open");

    if(open != NULL) {
        ui->answerLabel->setText("SUCCESS");
    }
    else {
        ui->answerLabel->setText("ERROR");
    }
}
Was it helpful?

Solution

You are testing same string every time, see this:

char enteredCmd[4096];
strcpy(enteredCmd, "Some string data");
text = enteredCmd;

this overrides text value with copy of this "Some string data" string.

Anyway you made this to complicated. QString have lots of functionality useful for you.

void MainWindow::on_consoleEdit_returnPressed()
{
    QString text = ui->consoleEdit->text();

    if(text.contains("open")) {
        ui->answerLabel->setText("SUCCESS");
    } else {
        ui->answerLabel->setText("ERROR");
    }
}

OTHER TIPS

Your code is not searching on the text from the line edit. Your code is actually searching for "open" on the string enteredCmd, which always contains "Some string data". Thus, you should always get "ERROR" printed to your answer label.

Here's what I think you are trying to do, using QString instead of strstr:

void MainWindow::on_consoleEdit_returnPressed()
{
    QString text = ui->consoleEdit->text();

    if(text.contains(QStringLiteral("open"))) {
        ui->answerLabel->setText("SUCCESS");
    }
    else {
        ui->answerLabel->setText("ERROR");
    }
}

QString is designed to work with many languages so it requires some conversion to get text to a C style eight bit string. You might try something like this:

char *myChar = text.toLatin1().data();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top