【发布时间】:2021-11-16 23:58:01
【问题描述】:
我尝试使用字符串的算法排列。 如果我这样做效果很好
void MainWindow::on_algo_clicked()
{
QString letters;
letters = this->ui->myletters->text();
QMessageBox msgbox;
msgbox.setText(letters);
msgbox.exec();
string lettersString = letters.toUtf8().data();
char str[] = "ABC";
int n = strlen(str);
permute(str, 0, n-1);
}
与char str[] = "ABC"
我想用字母的值(qlineedit)替换“ABC”。我可以在 QMessageBox 中显示字母。
我尝试了很多转换来将 QString“字母”转换为字符串值(letters.toUtf8 .to StdString ........)但是这部分代码总是有一些错误:char str[] = lettersString;
我真的不明白。
我在这里和互联网上阅读了很多主题,但没有任何效果。
我确定我误会了什么。
经过数小时的研究和大量尝试,我编写了这段代码,它似乎可以用我的 Qlineedit 中的字母进行排列。
但是我不明白它为什么起作用以及为什么我不能使用 c_str 或其他解决方案。
如果我不完全了解流程,这不是一个好的解决方案。 ;-)
void MainWindow::on_algo_clicked()
{
QString letters = this->ui->myletters->text();
//QMessageBox msgbox;
//msgbox.setText(letters);
//msgbox.exec();
//string lettersString = letters.c_str();
//std::string lettersString;
QByteArray arraylettersUTF8 = letters.toUtf8();
char* lettersString = arraylettersUTF8.data();
QMessageBox msgbox;
msgbox.setText(lettersString);
msgbox.exec();
//lettersString = letters.toStdString();
char* str = lettersString;
int n = strlen(str);
permute(str, 0, n-1);
}
【问题讨论】:
-
std::string与char []不同。要么将QString转换为char*,使用letters.toLatin1().data()之类的东西,要么使用lettersString.c_str()转换你的std::string。 -
我尝试使用 lettersSting.c_str() 但 c_str() 未被识别为函数。也许我忘记了标题中的#include。我的#include 是#include
#include #include "mainwindow.h" #include "ui_mainwindow.h" #include #include #include #include #include -
也许我看错了你的代码。您的代码中的
string是什么?我以为是std::string,但肯定是别的东西? -
"letters" 是一个 QString,我尝试将其转换为与 char str[] = lettersString; 一起使用的标准字符串,例如