2014-03-19 120 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();