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 !

有帮助吗?

解决方案

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;
       }

其他提示

You should use QStringList instead of QString [1000];.

Then you can add line simply with

peoples << line;

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

peoples[i] = line;

But you'd better use first approach.

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 QStringList instead 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 pepoles like this;

QStringList pepoles;

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

pepoles << line;

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

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

std::vector<QString> pepoles;

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

pepoles.push_back(line);

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

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

Also this will show the first line only :

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

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

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

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

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

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.

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.".

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:

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.

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:

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.

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.

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:

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);

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:

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??

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top