know the number of columns from text file, separat

2019-02-27 03:17发布

问题:

I need to know the number of columns from a text file with floats.

I've made like this to know the number of lines:

inFile.open(pathV); 

// checks if file opened
if(inFile.fail()) {
    cout << "error loading .txt file for reading" << endl; 
    return;
}
// Count the number of lines
int NUMlines = 0;
while(inFile.peek() != EOF){
    getline(inFile, dummyLine);
    NUMlines++;
}
inFile.close();
cout << NUMlines-3 << endl; // The file has 3 lines at the beginning that I don't read

A line of the .txt :

189.53  58.867  74.254  72.931  80.354

The number of values can vary from file to file but not on the same file.

Each value have a variable number of decimal places after the "." (dot)

The values can be separated by a space or a TAB.

Thank you

回答1:

Given a line you have read, called line this works:

std::string line("189.53  58.867  74.254  72.931  80.354");
std::istringstream iss(line);
int columns = 0;
do
{
    std::string sub;
    iss >> sub;
    if (sub.length())
        ++columns;
}
while(iss);

I don't like that this reads the whole line, and then reparses it, but it works.

There are various other ways of splitting strings e.g. boost's <boost/algorithm/string.hpp> See previous post here



回答2:

You can read one line, then split it and count number of elements.

Or you can read one line, then iterate through it as an array and count number of space and \t characters.



回答3:

You can do this very easily if these three assumptions are true:

  1. dummyLine is defined so that you have access to it outside the while loop scope
  2. The last line of the file has the same tab/space delimited format (Cause that's what dummyLine will contain after the while loop)
  3. One and only one tab/space occurs between numbers on each line

If all these are true, then right after the while loop you'll just need to do this:

const int numCollums = std::count( dummyLine.begin(), dummyLine.end(), '\t' ) + std::count( dummyLine.begin(), dummyLine.end(), ' ' ) + 1;