2014-03-19 121 views
0

我是一個初學者,做了一個函數,它接受來自lineedit的輸入將其轉換爲數組,然後搜索它以查找單詞。如果找到這個單詞,它會在標籤上打印成功,否則會打印錯誤。問題是無論我輸入什麼,它都會打印錯誤。 我在做什麼錯。qt程序中strstr的奇怪行爲

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"); 
    } 
} 

回答

1

您每次測試相同的字符串,請參閱本:

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

這將覆蓋text值與此「一些字符串數據」字符串的副本。

無論如何,你使這變得複雜。 QString有很多對您有用的功能。

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

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

你的代碼是不是從行編輯文本搜索。您的代碼實際上是在字符串enteredCmd上搜索「打開」,該字符串始終包含「某些字符串數據」。因此,您應始終將「錯誤」打印到您的答案標籤上。

這就是我認爲你正在嘗試做的,使用的QString代替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"); 
    } 
} 
+0

你爲什麼使用QStringLiteral函數? –

+0

@ TheExperimenter請參閱http://woboq.com/blog/qstringliteral.html –

0

QString的設計,因此需要一些轉換得到的文本與C風格的八位串在許多語言工作。你可能會嘗試這樣的:

char *myChar = text.toLatin1().data();