Search code examples
c++qtqfile

finding largest number Qt


How to find a largest number from a File in Qt. Could anybody explain to me in detail, as I am new to Qt.

I've already tried but i am not able to understand. Here I took a file from the folder which contains 2000 ints (numbers). I converted string to int and now I want to find the largest number among all the int's in file:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include <QFile>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}
QString ReadAll;
int i;
//int iMax = array[0];

void MainWindow::on_pushButton_pressed()
{

    QFile file("/home/path");
    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug()<<"error";
    }
    QTextStream in(&file);


    while(!in.atEnd())
    {
        qDebug()<<ReadAll;
      ReadAll=in.readAll();
        qDebug()<<ReadAll;
    }
    file.close();
        qDebug()<<ReadAll;

        QStringList List=ReadAll.split(QRegExp("\n"),QString::SkipEmptyParts);
        int StrListInt[List.count()];

        i=0;

        foreach(QString Str, List)
        {
            qDebug()<<Str;

            StrListInt[i]=Str.toInt();
            qDebug()<<"spliting"<<QString::number(StrListInt[i]);
        }

    ui->textEdit->setText(ReadAll);

}

Solution

  • Your code is wrong so I would decide to completely rewrite it.

    I think this would be the correct approach:

    • read line by line.

    • convert the line to Int.

    • use qMax() for updating the current maximum if needed.

      QFile file(QStandardPaths::locate(QStandardPaths::HomeLocation));
      if (!file.open(QIODevice::ReadOnly))
          qDebug() << file.errorString();
      
      QTextStream in(&file);
      
      QString string;
      int currentMaximum = INT_MIN;
      
      while (!in.atEnd()) {
          string = in.readLine();
          currentMaximum = qMax(currentMaximum, string.toInt());
      }
      

    Disclaimer: I would not personally use Qt for such a simple task, just the standard library in C++.