0

I'm reading a matrix of unknown size from a .csv file and I was wondering, does the last row always finish with '\n' ? How can I know if it doesn't?

Here's my way of counting the rows

N=1
while(!fin.eof()){
    bool nonemptyrow=0;
    string line;
    getline(fin,line);
      //analize the elements of the line (in particoular set nonemptyrow=1
      // if the row is well formatted (i.e. there is no wild '\n' in the file)
    N=N+nonemptyrow;
 }

but of course I get different values of N if the last element of the file is a '\n' or an element of the matrix!

consider the input file

1,2,3,4\n 1,2,3,4\n 1,2,3,4\n

this would tell me N=3, but the (almost) identical file, which looks well formatted to me

1,2,3,4\n 1,2,3,4\n 1,2,3,4

returns me N=2

Since this is an assignement which has to be evaluated, I'd like to be able to handle both input files without knowing a-priori which format will it be!

Does anyone have a solution? I'm reading a matrix of unknown size from a .csv file and I was wondering, does the last row always finish with '\n' ? How can I know if it doesn't?

Here's my way of counting the rows

N=1
while(!fin.eof()){
    bool nonemptyrow=0;
    string line;
    getline(fin,line);
      //analize the elements of the line (in particoular set nonemptyrow=1
      // if the row is well formatted (i.e. there is no wild '\n' in the file)
    N=N+nonemptyrow;
 }

but of course I get different values of N if the last element of the file is a '\n' or an element of the matrix!

consider the input file

1,2,3,4\n 1,2,3,4\n 1,2,3,4\n

this would tell me N=3, but the (almost) identical file, which looks well formatted to me

1,2,3,4\n 1,2,3,4\n 1,2,3,4

returns me N=2

Since this is an assignement which has to be evaluated, I'd like to be able to handle both input files without knowing a-priori which format will it be!

Does anyone have a solution?

mariob6
  • 379
  • 5
  • 13

1 Answers1

0

There lots of ways to count real (not empty) lines, e.g.:

    while (!ifs.eof()) {
        string line;
        getline(ifs,line);
        if( line.length() > 0 )
        {
            N++;
        }
    }

One more example:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
    ifstream ifs;
    int N = 0;
    ifs.open ("t1.txt", std::ifstream::in); // just open some file
    string line;
    while ( getline(ifs, line) ) // read line and check the stream state
    {  
        // count line
        N++;
        // process the line
        cout << line << "<" << endl; // that is just example
    }
    ifs.close();
    cout << "Number of lines is " << N << endl;
    return 0;
}
VolAnd
  • 6,034
  • 3
  • 19
  • 40