4

I am trying to read values from a text file using the Qt code given below.

int ReadFromFile(QString fileName)
{
   QFile file(fileName);
   if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
      return 1;

   QTextStream in(&file);
   while (!in.atEnd())
   {
      QString line = in.readLine(1); //read one line at a time
      QStringList lstLine = line.split(",");
   }
   file.close();
   return 0;
}

The content of the text file is as follows:

1,0.173648178  
2,0.342020143  
3,0.5  
4,0.64278761  
5,0.766044443  
6,0.866025404  

However readLine always returns one character at a time but my intention is to read one line at a time and to split each line to get the individual comma seperated values.

Am I missing something basic here?

Mat
  • 202,337
  • 40
  • 393
  • 406
Martin
  • 3,396
  • 5
  • 41
  • 67

3 Answers3

6

Yes. You're passing 1 for the maxlen parameter, which means to limit the line length to only 1 character. Try it without supplying anything for maxlen.

kenrogers
  • 1,350
  • 6
  • 17
  • when i try that way, readLine returns the contents of more than one line! – Martin Mar 30 '12 at 12:25
  • Hmm, I can't duplicate that. Using the data you supplied, readLine() works fine for me. – kenrogers Mar 30 '12 at 13:16
  • 2
    The problem was that the lines were incorreclty terminated by "\r", the lines did not have has correct trailing end-of-line characters "\r\n" – Martin Apr 02 '12 at 04:48
1

I know this might be an old post but it looks like you are overwriting your lstLine variable during each iteration.

This one:

QStringList lstLine = line.split(",");

Change to

int ReadFromFile(QString fileName)
{
   QStringList lstLine;
   QFile file(fileName);
   if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
      return 1;
   QTextStream in(&file);
   while (!in.atEnd())
   {
      QString line = in.readLine(); //specifying number = # of characters
      lstLine.append( line.split(",") );
   }
   file.close();
   return 0;
}
DevHelper
  • 11
  • 1
1

remove zero from your code and try..

   QTextStream in(&file);
   while (!in.atEnd())
   {
      QString line = in.readLine(); //read one line at a time
      QStringList lstLine = line.split(",");
   }
shofee
  • 2,079
  • 13
  • 30