0

我加载一个文件,需要计算其中的元素数量,如下所示:

int kmean_algorithm::calculateElementsInFile()
{
    int numberOfElements = 0;
    int fileIterator
    QFile file("...\\iris.csv");
    if(!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(0, "Error", file.errorString());
    }
    if(file.isOpen())
    {
        while(file >> fileIterator)
        {
            numberOfElements ++;
        }
    }
    file.close();
}

提供的代码是错误的,我意识到它是错误>>fstream(如果我使用标准 c++ 加载文件,如下所示ifstream file(filename);没有问题),因为我使用QFile它加载文件意味着file >> fileIterator不可能出现以下关于类型不等的错误:

错误:'operator>>' 不匹配(操作数类型是 'QFile' 和 'int')

问:我怎样才能使>>我的情况正常工作?有什么建议吗?备择方案?

4

1 回答 1

0

QTextStream 类允许您使用 QIODevice 构造它,这恰好是 QFile 的派生源。因此,您可以执行以下操作:-

QFile file(".../iris.csv"); // Note the forward slash (/) as mentioned in the comments
if(!file.open(QIODevice::ReadOnly))
{
    QMessageBox::warning(0, "Error", file.errorString());
}

// Use a text stream to manipulate the file
QTextStream textStream(&file);

// use the stream operator, as desired.
textStream >> numberOfElements;

请注意,Qt 可以接受路径中的单个正斜杠 (/),而不是所有路径的转义反斜杠 (\\)。正斜杠也是在 Windows 以外的操作系统(如 Linux 和 OSX)中定义路径的常用方式。

于 2013-08-23T07:46:48.960 回答