How to add data in array QT C++
Solution 1
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;
}
Solution 2
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.
Solution 3
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 ;)
Solution 4
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.
Random78952
Updated on October 02, 2020Comments
-
Random78952 over 3 years
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 !
-
Random78952 over 11 yearsCan i declare pepoles array without size ?
-
Jason over 11 yearsNo. If you want to not limit the size use QStringList as in Nikos' suggestion.
-
Anthony over 11 yearsThis also seems like a good fit for QVarLengthArray.