know the number of columns from text file, separated by space or tab

不问归期 提交于 2019-12-02 05:21:48

问题


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;


来源:https://stackoverflow.com/questions/20566520/know-the-number-of-columns-from-text-file-separated-by-space-or-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!