有没有错误loginDialog::loginDialog(QWidget *parent) : QDialog(parent), ui(new Ui::loginDialog) { loginDialog::ui->setupUi(this); loginDialog::ui->lineEditPassword->setEchoMode(QLineEdit::Password); setWindowTitle("Login"); } void loginDialog::on_buttonLogin_clicked() { student* newStudent = new student; static int count=0; QString filePath = QCoreApplication::applicationDirPath() + "/student.txt"; QFile file(filePath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "Could not open file" << filePath; return; } QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); if(line == "end"){ break; } QStringList data = line.split(" "); newStudent->m_name = data[0]; newStudent->m_ID = data[1]; if(loginDialog::ui->lineEditID->text()==newStudent->m_name){ break; } } if (loginDialog::ui->lineEditPassword->text()==newStudent->m_ID) { accept(); } else { count++; qDebug()<<count; if(count>2) { this->close(); // 3次错误退出 } else { /* QMessageBox::warning(NULL,"warning",newStudent->m_name+newStudent->m_ID);*/ QMessageBox::warning(NULL, "warning","Account password error,please login again.you have "+QString::number(3-count)+" chances"); } } delete newStudent; file.close(); }
时间: 2024-01-18 12:05:16 浏览: 121
LoginDialog:登录向导
在这段代码中,有一个潜在的问题。
在while循环中,如果没有找到匹配的用户名,就会退出循环,但此时newStudent对象并没有被正确地初始化,因此在后面比较密码时可能会导致未定义的行为。为了解决这个问题,可以将newStudent对象的初始化移动到while循环之前,这样即使没有找到匹配的用户名,newStudent对象也会被正确地初始化。
另外,需要注意的是,如果密码不匹配,应该在while循环之后再删除newStudent对象,否则可能会导致未定义的行为,因为newStudent对象可能没有被正确地初始化。
下面是修改后的代码:
```
loginDialog::loginDialog(QWidget *parent) : QDialog(parent), ui(new Ui::loginDialog) {
loginDialog::ui->setupUi(this);
loginDialog::ui->lineEditPassword->setEchoMode(QLineEdit::Password);
setWindowTitle("Login");
}
void loginDialog::on_buttonLogin_clicked() {
student* newStudent = new student;
QString filePath = QCoreApplication::applicationDirPath() + "/student.txt";
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Could not open file" << filePath;
return;
}
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
if(line == "end"){
break;
}
QStringList data = line.split(" ");
newStudent->m_name = data[0];
newStudent->m_ID = data[1];
if(loginDialog::ui->lineEditID->text()==newStudent->m_name){
break;
}
}
file.close();
if(newStudent->m_name.isEmpty()){
// 没有找到匹配的用户名
delete newStudent;
QMessageBox::warning(NULL, "warning", "No user found");
return;
}
if (loginDialog::ui->lineEditPassword->text()==newStudent->m_ID)
{
accept();
}
else
{
static int count=0;
count++;
qDebug()<<count;
if(count>2)
{
this->close(); // 3次错误退出
}
else
{
QMessageBox::warning(NULL, "warning", "Account password error, please login again. You have "+QString::number(3-count)+" chances");
}
}
delete newStudent;
}
```
阅读全文