if crash when comparing qstrings
I was trying to make a login and registration.
i am saving the credencials on text file, and for the login i use a if statement to compare what the user typed and the credencials saved on the file.
But my if is not working, the program crashes when it "enter".
currently my if is inside the while loop for the read file.
when i tryed to use it outside the QString username and QString password
it was saying they where not declared.
here is the code:
void MainWindow::on_pushButton_Login_clicked()
{
QString usernamelogin = ui->lineEdit_username->text();
QString passwordlogin = ui->lineEdit_password->text();
QFile file("C:/Users/luisp/Desktop/poo/janela_de_login/Credencials/UsersInfo.txt");
if(!file.open(QFile::ReadOnly | QFile::Text)){
// QMessageBox::Warning(this,"Aviso", "file not open");
}
QTextStream in(&file);
while(!in.atEnd())
{
QString line = in.readLine();
QStringList credencials = line.split("\n");
QString username = credencials[1];
QString password = credencials[2];
file.flush();
file.close();
if (username == usernamelogin && password == passwordlogin){
//QMessageBox::information(this, "Login", "Username and password correct");
ui->statusbar-> showMessage("Username e password correct", 3000);
}
else{
//QMessageBox:: warning(this, "Login","Username e password not correct");
ui->statusbar-> showMessage("Username e password not correct", 3000);
}
}
}
void MainWindow::on_pushButton_Register_clicked()
{
QFile file("C:/Users/luisp/Desktop/poo/janela_de_login/Credenciais/UsersInfo.txt");
if(!file.open(QFile::WriteOnly | QFile::Text)){
// QMessageBox::Warning(this,"warning", "file not open");
}
QTextStream out(&file);
QString email = ui->Email_Register->text();
out << email << '\n';
QString username = ui->Username_Register->text();
out << username << '\n';
QString password = ui->Password_Register->text();
out << password << '\n';
file.flush();
file.close();
}
Solution 1:
There are a couple of problems I see, '\n' typically indicates a new line so is your username and password on different lines in the file? If not then obviously your problem is they are not on the same line. If you for some odd reason have username\npassword\n all in the same line, then you quite possibly are running off the end of the array returned by QString.split('\n') as it should return them in credentials[0] and credentials[1].