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

前端 未结 3 960
一个人的身影
一个人的身影 2021-01-22 07:01

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 f         


        
相关标签:
3条回答
  • 2021-01-22 07:29

    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

    0 讨论(0)
  • 2021-01-22 07:36

    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.

    0 讨论(0)
  • 2021-01-22 07:37

    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;
    
    0 讨论(0)
提交回复
热议问题