How to add data in array QT C++

Random78952 picture Random78952 · Oct 25, 2012 · Viewed 25.1k times · Source

I want to read line by line a text file and add each line in a array, I try something like that, but something is wrong with my array, what ?

QFile inputFile("C:\\pepoles.txt");
if (inputFile.open(QIODevice::ReadOnly))
{
    QTextStream in(&inputFile);
    QString pepoles[1000];
    while ( !in.atEnd() )
    {
        QString line = in.readLine();
        pepoles[] = line;
    }
    ui->lineEdit->setText(pepoles[0]);
}
else{
    QMessageBox::critical(this, "Ouups",
                          "Le fichier est introuvable ou vide...");
}

inputFile.close();
}

Thanks !

Answer

Jason picture Jason · Oct 25, 2012

Keep track of the number of lines you've read, and index pepoles with it. Also, make sure you don't exceed your arrays capacity.

   int lineNum = 0;
   QFile inputFile("C:\\pepoles.txt");
   if (inputFile.open(QIODevice::ReadOnly))
   {
      QTextStream in(&inputFile);
      QString pepoles[1000];
      while ( !in.atEnd() && lineNum < 1000)
      {
         QString line = in.readLine();
         pepoles[lineNum++] = line;
       }