Mark Thompson
Mark Thompson

Reputation: 13

How can I check if a file contains only integers?

In my project I need to upload a file and check that inside it there is an integer (positive or negative) for each line so that it can be represented within a vector.

Since I am working on QT and C++ I have considered two proposals, but both when I insert a number in the file for example "35.2" with a comma and I press the start button the program crashes.

Is there a better solution to mitigate the problem? I am attaching one of the solution that I was evaluating.

QFile file_in(file_name);

file_in.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream in(&file_in);
int elem;
int pos = 0;
QString s;
QIntValidator valid(-999, 999, this);

while(!in.atEnd())
{
    in >> elem;
    s = QString::number(elem);
    if(!valid.validate(s,pos))
    {
        v.clear();
        QMessageBox msg(this);
        msg.setText("Input non valido");
        msg.exec();
        return;
    }
    else
    {
        v.push_back(elem);
    }
}

Upvotes: 1

Views: 594

Answers (2)

Please read the doc about validate method here:

https://doc.qt.io/archives/qt-4.8/qintvalidator.html#validate

you are using a criteria for valid inputs as valid(-999, 999, this);

so if the list in the file is holding a row with 1000, using a toInt method will return you a false positive result!

the result is not just True or False like you may think...

you actually get:

enter image description here

Upvotes: 1

Fareanor
Fareanor

Reputation: 6805

A simpler solution would be to read the file line by line and check if the current line is convertible to an integer.

Qt already provides a lot of convenience methods. For instance, you would be interested by QByteArray::toInt().

Hence a solution could be:

bool validate(const QString & file_name)
{
    QFile in_f(file_name);
    if(!in_f.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;

    bool is_valid = true;
    while(is_valid && !in_f.atEnd())
    {
        QByteArray line = in_f.readLine();
        line.toInt(&is_valid); // is_valid is set to false if the conversion failed
    }
    return is_valid;
}

This way there is no crash. If each line contains an integer, it will return true, otherwise, if at least one line contains something else (string, double, ...), it will return false.

As implemented here, if the file is empty, the function will return true. Of course you can add a check for this case if you want to return false instead.

Upvotes: 2

Related Questions