Read the data from the file and keep it in a QHash as follows:

 QHash<int, QVector<float> >

My data file doesn't contain headers, so when I first create vectors and then enter the file loop I miss the data which is on the first line. My source is :

    QFile file("...\\a.csv");
    if(!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(0, "Error", file.errorString());
    }

    QString fileLine = file.readLine();
    QStringList fileLineSplit = fileLine.split(',');
    hashKeySize = fileLineSplit.size();

    for(int t=0; t<hashKeySize; t++)
    {
        QVector<float> vec;
        hash_notClustered[t] = vec;
    }

    while(!file.atEnd())
    {
        QString line = file.readLine();
        QStringList list = line.split(',');
        for(int t = 0; t<list.size(); t++)
        {
            hash_notClustered[t].push_back(list[t].toFloat());
        }
    }

Q: how can I get the pointer back to the first line when looping with while(!file.atEnd()) not to miss the first line?

有帮助吗?

解决方案

Closing the file with file.close()

for(int t=0; t<hashKeySize; t++)
    {
        QVector<float> vec;
        hash_notClustered[t] = vec;
    }

and reopening it before while(!file.atEnd()){...} solves the issue.

其他提示

Resetting the QFile is one way. There might be others. Look at this code:

    QFile file("...\\a.csv");
    if(!file.open(QIODevice::ReadOnly)){
        QMessageBox::warning(0, "Error", file.errorString());
    }

    QString fileLine = file.readLine();
    QStringList fileLineSplit = fileLine.split(',');
    int hashKeySize = fileLineSplit.size();

    for(int t=0; t<hashKeySize; t++){
        QVector<float> vec;
        hash_notClustered[t] = vec;
    }

    do{
        for(int t = 0; t<fileLineSplit.size(); t++){
            hash_notClustered[t].push_back(list[t].toFloat());
        }
        fileLine      = file.readLine();
        fileLineSplit = fileLine.split(',');
    }while(!fileLine.isEmpty());

C++ has more loops than the 'for' and 'while' loop. Is above code more efficient? Faster? Bug free? No idea. But at least on file operation less. :-)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top