c++ - QT C++ 读取每行同时包含 int 和 QString 的文件

标签 c++ string qt

我试图读入一个文本文件,然后将每一行解析为 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/

相关文章:

c++ - 使用QT查看来自相机的流图像

c++ - 拖放到桌面或特定文件夹中,无需临时存储。

c++ - 错误 : '::main' must return 'int'

c# - Windows 拖放通知

android - String[] a 和 String a[] 的区别

ruby - 按字符串中的数字对 Ruby 字符串数组进行排序

string - 验证一个字符串是否包含在 Lisp 中的另一个字符串中的函数

c++ - 如何为包装需要 2 个参数的 c 函数的 unique_ptr 类成员创建自定义删除器?

c++ - 在编译时选择全局作用域函数

c++ - gdb 找不到运算符 []