Using iomanip to format data output to a text file with Qt

I am a student programmer using QT for development and application for work. I am currently developing save functions where data is taken from a table and saved to a file. I am having problems when I try to write data to columns. Don't confuse anyone; my problem is formatting WHEN SAVING text from data table; without reading it. So when data is saved from my table, it is saved to a file and looks like this:

0 0.048 300 101325 0 0
10 0.048 300 101325 0 0

      

I need it to look like

0  0.048 300 101325 0 0
10 0.048 300 101325 0 0

      

While researching, I came across setw from the iomanip library in C ++, which sets the minimum number of characters to fill the data and then uses the rest as an addition. Sounds great? The problem is, I can't get it to work with anything other than cout; why I don't need it. I need them to basically add spaces to my string before they are written out.

I also feel like Qt probably has something to help me accomplish what I need (much easier). I just can't find this member function after confirming the QString documentation , QStringList Doucmentation , and most of all the QTextStream Documentation.

Currently my save function looks like this:

QTextStream data(&saveFileAsscf);
QStringList tmpList;
for (int x = 0; x<ui->tableWidgetReaderTable->rowCount(); x++)
                {
                    strList.clear();
                    for(int a = 0; a < ui->tableWidgetReaderTable->columnCount(); a++)
                    {
                        strList << ui->tableWidgetReaderTable->item(x,a)->text();
                    }
                    data <<strList.join(" ") << "\n";
                }

      

I'm so sure that setFieldWidth is my answer from the QTextStream Documentation , but I can't seem to get it to work correctly. Tried:

data.setFieldWidth(13) << strList.join(" ") << "\n";

      

I hope this is a simple answer for someone and I'm just stumbling across the writers block, but any help would be related to this. Thanks for reading my post, and I thank any help to fill the gap here!

+3


source to share


1 answer


std::fstream

is one option if you want to use STL. However, if you are treating the entire list of strings as a field you have a width that is much more than 13 in the example output you could try with setFieldWidth(23)

, but that will probably be the end. If you treat each value as a field then it gets easier.

An example of what I mean by treating each value as a field:



QTextStream data(&saveFileAsscf);
for (int x = 0; x<ui->tableWidgetReaderTable->rowCount(); x++)
{
   data.setPadChar(' ');
   for(int a = 0; a < ui->tableWidgetReaderTable->columnCount(); a++)
   {
      QString value = ui->tableWidgetReaderTable->item(x,a)->text();
      data.setFieldWidth(qMax(2, value.length()));
      data << value;
      data.setFieldWidth(1);
      data << " ";
   }
   data << "\n";
}

      

+2


source







All Articles