我试图读入一个文本文件,然后将每一行解析为 3 个变量。其中两个是 QStrings
,其中一个是 int
。文件的每一行将如下所示:
This is my first string : This is my second string : 2
This is another first string : This is another second string : 18
基于此,当我遍历我的文件时,我想设置每个变量(QString1、QString2、int),然后调用一个方法。
QString1 = "This is my first string";
QString2 = "This is my second string";
int x = 2;
callMethod(QString1, QString2, x);
QString1 = "This is another first string";
QString2 = "This is another second string";
int x = 18;
callMethod(QString1, QString2, x);
我该怎么做?
最佳答案
您可以逐行读取文件,然后在结果流过时简单地解析结果。这是一个例子:
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
#include <QDebug>
void MainWindow::parseFile()
{
QFile inputFile(QFileDialog::getOpenFileName());
if (inputFile.open(QIODevice::ReadOnly))
{
QTextStream in(&inputFile);
while (!in.atEnd())
{
QString text = in.readLine();
if (!text.isEmpty())
{
QStringList line = text.split(':');
callMethod(line[0], line[1], QString(line[2]).toInt());
}
}
inputFile.close();
}
}
void MainWindow::callMethod(QString first, QString second, int third)
{
qDebug() << "Variable #1: " << first;
qDebug() << "Variable #2: " << second;
qDebug() << "Variable #3: " << third;
}
关于c++ - QT C++ 读取每行同时包含 int 和 QString 的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37902620/