我加载了一个文件,需要按以下方式计算其中的元素数:
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++加载文件,如下所示,那么没有问题),因为我使用QFile加载文件,这意味着file >> fileIterator是不可能的,关于类型不平等的错误如下:
错误:不匹配“operator>>”(操作数类型为“QFile”和“int”)
问:我如何使>>在我的情况下起作用?有什么建议吗?其他选择?
发布于 2013-08-23 07:46:48
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 )中定义路径的正常方式。
https://stackoverflow.com/questions/18391220
复制相似问题