如何在数组中添加数据 QT C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13076388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:56:02  来源:igfitidea点击:

How to add data in array QT C++

c++arraysqtqt-creatorqfile

提问by Random78952

I want to read line by line a text file and add each line in a array, I try something like that, but something is wrong with my array, what ?

我想逐行读取文本文件并将每一行添加到数组中,我尝试了类似的操作,但是我的数组有问题,怎么办?

QFile inputFile("C:\pepoles.txt");
if (inputFile.open(QIODevice::ReadOnly))
{
    QTextStream in(&inputFile);
    QString pepoles[1000];
    while ( !in.atEnd() )
    {
        QString line = in.readLine();
        pepoles[] = line;
    }
    ui->lineEdit->setText(pepoles[0]);
}
else{
    QMessageBox::critical(this, "Ouups",
                          "Le fichier est introuvable ou vide...");
}

inputFile.close();
}

Thanks !

谢谢 !

回答by Jason

Keep track of the number of lines you've read, and index pepoles with it. Also, make sure you don't exceed your arrays capacity.

跟踪您已阅读的行数,并用它来索引人。另外,请确保不要超出阵列容量。

   int lineNum = 0;
   QFile inputFile("C:\pepoles.txt");
   if (inputFile.open(QIODevice::ReadOnly))
   {
      QTextStream in(&inputFile);
      QString pepoles[1000];
      while ( !in.atEnd() && lineNum < 1000)
      {
         QString line = in.readLine();
         pepoles[lineNum++] = line;
       }

回答by Lol4t0

You should use QStringListinstead of QString [1000];.

你应该使用QStringList而不是QString [1000];.

Then you can add line simply with

然后你可以简单地添加行

peoples << line;


Now your syntax is incorrect. You are trying to assign lineto an array, or what? You can only assign lineto the specified elementof array, like

现在你的语法不正确。您正在尝试分配line给一个数组,还是什么?您只能分配line给数组的指定元素,例如

peoples[i] = line;

But you'd better use first approach.

但你最好使用第一种方法。

回答by Nikos C.

You need to specify at which position you want to copy the string. For example:

您需要指定要复制字符串的位置。例如:

pepoles[0] = line;

will copy the string to the first element of the array. Obviously you will need a variable to iterate over the array, so that in each loop you'll copy the new string to the next position in the array.

将字符串复制到数组的第一个元素。显然,您将需要一个变量来遍历数组,以便在每个循环中将新字符串复制到数组中的下一个位置。

You should probably use a QStringListinstead of an array to make things easier and safer, so that you won't write past the end of the array by accident. For example, you can define a pepoleslike this;

您可能应该使用 aQStringList而不是数组来使事情变得更容易和更安全,这样您就不会意外地写到数组的末尾。例如,您可以pepoles像这样定义一个;

QStringList pepoles;

Then, every time you want to append a new string to the end, you do:

然后,每次您想在末尾追加一个新字符串时,您都可以执行以下操作:

pepoles << line;

Here's the documentation of QStringListon how to use it: http://doc.qt.digia.com/qt/qstringlist.html#details

这是QStringList有关如何使用它的文档:http: //doc.qt.dgia.com/qt/qstringlist.html#details

You can also use an std::vector<QString>instead:

您也可以使用一个std::vector<QString>代替:

std::vector<QString> pepoles;

In that case, you insert strings at the end with:

在这种情况下,您可以在末尾插入字符串:

pepoles.push_back(line);

Read up on std::vectorhere: http://www.cplusplus.com/reference/stl/vector

std::vector这里阅读:http: //www.cplusplus.com/reference/stl/vector

std::vectoris not part of Qt. It's provided by the standard C++ library.

std::vector不是 Qt 的一部分。它由标准 C++ 库提供。

回答by gogoprog

Also this will show the first line only :

这也将只显示第一行:

ui->lineEdit->setText(pepoles[0]);

You probably want something like this (if pepoles is a QStringList)

你可能想要这样的东西(如果 pepoles 是一个 QStringList)

ui->lineEdit->setText(pepoles.join());

The join() method will make a QString that concatenates all items in the qstringlist

join() 方法将创建一个连接 qstringlist 中所有项目的 QString

Edit: And maybe use something else than a LineEdit ;)

编辑:也许可以使用 LineEdit 以外的其他东西;)

回答by oOpSgEo

This question really depends on quite a few things. What is planned for the information you are abstracting from the text file. Are you to output it to another text file, display it in a widget with Text Object capabilities (i.e. QTextEdit, QLineEdit etc...), send it to a database, use it for a sort of some kind (i.e. delete duplicate entries or delimit/delete line spacing)? Is the Text file in question linewrapped? How many characters are in each line, hence how many bits.

这个问题实际上取决于很多事情。您从文本文件中提取的信息的计划是什么。您是否要将其输出到另一个文本文件,将其显示在具有文本对象功能(即 QTextEdit、QLineEdit 等)的小部件中,将其发送到数据库,将其用于某种类型(即删除重复条目或分隔/删除行间距)?有问题的文本文件是否换行?每行有多少个字符,因此有多少位。

I say this, for many reasons. As we all know Qt enriches the C++ language with Meta-Object-Compiler and extensive macros. Going back to the fundamentals of C++ programming in that macros rearrange the program text before the compiler actually sees it. I have found that in Qt this rings true more than anything with the Text Objects and File I/O to send to text objects. Once again it depends on how you have designed your application. It is best to follow Bjarne's advice and "Decide which classes you want, provide a full set of operations for each class, make commonality explicit by using inheritance. Where there is no such commonality, data abstraction suffices.".

我这么说,有很多原因。众所周知,Qt 通过元对象编译器和大量宏丰富了 C++ 语言。回到 C++ 编程的基础,宏在编译器实际看到它之前重新排列程序文本。我发现在 Qt 中,这比发送到文本对象的文本对象和文件 I/O 更真实。这再次取决于您如何设计您的应用程序。最好遵循 Bjarne 的建议和“决定你想要哪些类,为每个类提供全套操作,通过使用继承使共性显式。没有这种共性的地方,数据抽象就足够了。”。

Now that I have stated this you might have run time errors or the application crashes/finishes unexpectedly during or post compilation. Which means you'll have to rewrite the program/application to a count for your flow of data.

既然我已经说明了这一点,您可能会遇到运行时错误或应用程序在编译期间或编译后意外崩溃/完成。这意味着您必须将程序/应用程序重写为数据流计数。

If you you want the data from the text file so you can search/sort the text like a binary search algorithm to compare using one array like that will not work. if you want to display all the names in a text object and search for those you would be better off creating a QScrollArea and QTextEdit, and adding the QTextEdit to the QScrollArea like as shown below:

如果您想要文本文件中的数据,那么您可以像二进制搜索算法一样搜索/排序文本,以使用这样的数组进行比较是行不通的。如果要显示文本对象中的所有名称并搜索这些名称,最好创建一个 QScrollArea 和 QTextEdit,并将 QTextEdit 添加到 QScrollArea 中,如下所示:

scrollArea = new QScrollArea(this);
textEdit = new QTextEdit("",this);
textEdit -> setGeometry(QRect(QPoint(150, 50), QSize(400,20000)));
scrollArea -> setGeometry(QRect(QPoint(150, 50), QSize(400,300)));
scrollArea -> setWidget(textEdit);

*NOTE: you can set the size of your textedits length way beyond the size of the window! At least a thousand lines at 12 font??. Is 20000, 4 points north and south to contain line margin.

*注意:您可以将文本编辑长度的大小设置为超出窗口大小!12 种字体至少有一千行??。是20000,南北4点包含线边距。

if both the scrollarea and the textedit are created in the parent objects class, then read the file, use the readAll instead of readLine and just display it in the textEdit. A line edit for a thousand lines is massive!! You do not have to iterate and in such a case as what you are describing using the QFile::ReadOnly will suffice. If you do what is described in the parent object's class (i.e. main window), where the line edit creates a void function that reads the file, and display it as follows:

如果在父对象类中创建了 scrollarea 和 textedit,则读取文件,使用 readAll 而不是 readLine 并将其显示在 textEdit 中。一千行的行编辑是巨大的!!您不必迭代,在这种情况下,您使用 QFile::ReadOnly 描述的内容就足够了。如果您执行父对象的类(即主窗口)中描述的操作,其中行编辑会创建一个读取文件的 void 函数,并将其显示如下:

textEdit->setPlainText(line);

Then simply place a call to the function at the bottom of the mainWindow function. There is no point in creating an array to join the strings as described. When you can edit them much easier in the use of small three to five line functions using what I described.

然后只需调用 mainWindow 函数底部的函数即可。如上所述创建一个数组来连接字符串是没有意义的。当您使用我所描述的使用三到五行小功能时,可以更轻松地编辑它们。

If this application isn't for your use and you might want to go public: this would probably require computations by functions and data abstraction and input from/to the text objects post array filling. In this case create the container QStringList and use the qFill algorithm as shown below after the file closes.

如果此应用程序不供您使用,并且您可能想要公开:这可能需要通过函数和数据抽象进行计算,并在数组填充后从/到文本对象的输入。在这种情况下,创建容器 QStringList 并在文件关闭后使用 qFill 算法,如下所示。

QList<QString> Lstring(lineNumbers); //line numbers is the size of strings per line

qFill(Lstring, peoples.size());

foreach(QString item, Lstring){
    textObjectOfChoice -> setText();
}

I Personally would prefer to use a QStringList, create a boolean function in the MainWindow's class set to false (off), and in the int main{}, as soon as the app begins execution, and of course the MainWindow or dialoge object has been created call a dot seperater on that object and pass a true through the parameters turning your file load on once. Then AFTER calling w.show(); and BEFORE the recursive return app.exec(), recall the same dot seperator function and then pass the value to false. NOTE: Splash screens help with this. I personally have only gone as high as a Half-million words 2.5 million characters without splashcreen, It could go a lot longer depending on how many classes you personally have written in the application. Below is an example of a function that would be called:

我个人更喜欢使用 QStringList,在 MainWindow 的类中创建一个布尔函数设置为 false(关闭),并在 int main{} 中,一旦应用程序开始执行,当然 MainWindow 或 dialoge 对象已经created 在该对象上调用一个点分隔符,并通过参数传递一个 true 来打开您的文件加载一次。然后在调用 w.show(); 之后 在递归返回 app.exec() 之前,调用相同的点分隔符函数,然后将值传递给 false。注意:启动画面对此有帮助。我个人只有 50 万字 250 万个没有启动画面的字符,根据您个人在应用程序中编写的类的数量,它可能会更长。下面是一个将被调用的函数的例子:

void WordGame::fileStart(bool load){

    start = load;

    if (start){
        QFile myfile(":/WordGame/WordGame/TheHundredGrand.txt");

        if(myfile.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QString line;
            QTextStream stream(&myfile);
            int index = 0;
            int length = 0;
            do
            {
                line = stream.readLine();
                arryOne[index] = line;
                listOne << arryOne[index];
                index++;
                length++;
            }while(index<109582);

            stream.flush();
            myfile.close();
        }
    }
}

In the main the WordGame mainwindow class would be called as shown below: bool load = true; WordGame w; w.fileStart(load);

在主要的 WordGame 主窗口类将被调用如下所示: bool load = true; 文字游戏 w; w.fileStart(加载);

w.show();

w.fileStart(!load);

return app.exec();

This is of course you have the word list you were referring to in qrc source file. If you dont create the file load portion of the algorithm to quit after the first instance of the app is called the list will continue to expand repeating itself (Remember all c/c++ applications that have standard input/output are in themselves recurrsive, hence return app.exec). Abstracting the data to another list outside the function of the first list creation (meaning that the original list will be parsed) so it can be compared with the original, e.g. Already answered, previously answered, previously searched for etc.., is not the smartest move based on the amount of text objects. Its bested to just create another list of the users input and then iterate the initial list vs the list of user input. I would use the something like this:

这当然是您在 qrc 源文件中所指的单词列表。如果在调用应用程序的第一个实例后不创建要退出的算法的文件加载部分,则列表将继续重复扩展(请记住,所有具有标准输入/输出的 c/c++ 应用程序本身都是递归的,因此返回app.exec)。将数据抽象到第一个列表创建功能之外的另一个列表(意味着原始列表将被解析),以便可以将其与原始列表进行比较,例如已经回答、先前回答、先前搜索等,不是基于文本对象数量的最智能移动。最好只创建另一个用户输入列表,然后迭代初始列表与用户输入列表。我会使用这样的东西:

QStringList::iterator i3 = qFind(userInputList.begin(), userInputList.end(), word);
QStringList::iterator i2 = qFind(listOne.begin(), listOne.end(), word);

In the above iterators one finds if the user entries match the initial data set the other searches against the users previous inputs.

在上面的迭代器中,一个查找用户条目是否与初始数据集匹配,另一个搜索用户以前的输入。

NOTE: The Functions and or methods in C++ or Java should be 30 lines or less of data ( non-empty lines ) . To abstract and input data from widgets that have text object capabilities (i.e. lineEdit) repetitively, and to perform computations on them can lead to trouble later on if your opening the file frequently as described. It also looks like a connect statement should be in order after the file.closed() operation is complete to another function. Or the use of a boolean function done = true; which quite frankly is the best way to develop, large robust, software in Qt/Cpp (or in any language for that matter) is with binary (0 or 1) true or false, function/method completion. Creating a qrc file and adding the text file as file might also be of interest depending on your usage. Creating a one time opening and closing to fill your data container would be the way to go, out of main event loop. If you use the Qstringlist the list could continuously be filled until memory dumping is performed which then causes application failure. To avoid this and extra 'list-reset' function would be in order, like reverse iteration with "" as null for each index position of the list. If a upon a user hitting the enter button or something, or whatever it is you are developing, will it automatically call the function that contains TextStream object??

注意:C++ 或 Java 中的函数和/或方法应该是 30 行或更少的数据(非空行)。重复地从具有文本对象功能(即 lineEdit)的小部件中提取和输入数据,并对它们执行计算,如果您像描述的那样频繁打开文件,可能会导致稍后出现问题。在 file.closed() 操作完成到另一个函数之后,连接语句看起来也应该是有序的。或者使用布尔函数 done = true; 坦率地说,这是在 Qt/Cpp(或任何与此相关的任何语言)中开发大型健壮软件的最佳方式是二进制(0 或 1)真或假,函数/方法完成。根据您的使用情况,创建 qrc 文件并将文本文件添加为文件可能也很有趣。创建一次性打开和关闭以填充您的数据容器将是脱离主事件循环的方法。如果您使用 Qstringlist,则列表可能会不断填充,直到执行内存转储,然后导致应用程序失败。为了避免这种情况,额外的“list-reset”函数将是有序的,例如对列表的每个索引位置使用“”作为空的反向迭代。如果用户按下回车按钮或其他东西,或者你正在开发的任何东西,它会自动调用包含 TextStream 对象的函数吗??就像对于列表的每个索引位置,“”为空的反向迭代。如果用户按下回车按钮或其他东西,或者你正在开发的任何东西,它会自动调用包含 TextStream 对象的函数吗??就像对于列表的每个索引位置,“”为空的反向迭代。如果用户按下回车按钮或其他东西,或者你正在开发的任何东西,它会自动调用包含 TextStream 对象的函数吗??

P.S. If you really wanted to get righteous about it you could do it really old school like 8 bit style, *if you permenantly knew what the your text file was gonna be, and was immutable; and create (what is it???) int array[97], which is all the alplanumeric plus Capitals plus special characters/puncuation are equal to one index position of the array. For instance one integer is equal to one character e.g. [0]=a,[1]=b, [26]=A, and create a letter occurence program to count/chart the position of each character of each line, and then once you have the statistics for that particular word file or text file, iterate the int array back through a function that matches the integer to its correlating key input (via a temporary variable more than likely) and then into a QStringList which would then be reverse iterated to the text object that would be displayed to the user of your application.

PS 如果你真的想对它说正经,你可以像 8 位风格一样真正地做到老派,*如果你永远知道你的文本文件会是什么,并且是不可变的;并创建(它是什么???)int array[97],即所有的字母数字加大写字母加特殊字符/标点符号都等于数组的一个索引位置。例如一个整数等于一个字符,例如[0]=a,[1]=b,[26]=A,并创建一个字母出现程序来计算/绘制每行每个字符的位置,然后一次你有那个特定的 word 文件或文本文件的统​​计数据,