1

I am following the solution code by Loki Astari on

How can I read and parse CSV files in C++?

How can i write an iterator in the main function to count the number of columns from CSV header

int main()
{
    std::ifstream       file("plop.csv");

    for(CSVIterator loop(file); loop != CSVIterator(); ++loop)
    {
        //Instead of printing the 4th element as shown below, I want to  print all the
        //columns and thus determine the number of columns

         //std::cout << "4th Element(" << (*loop)[3] << ")\n";


    }
}

Here is an example header of a csv file I am working with

cmd, id, addr, qos, len, lock, prot, burst, size, cache, user, duser, dstrb, data

I want to print them using an iterator or some for loop and determine the number of columns which in this case is 14

Community
  • 1
  • 1
user2979872
  • 371
  • 5
  • 17

1 Answers1

1

If you read through the CSVIterator code, it makes use of the CSVRow class which has the following method:

std::size_t size() const
{
    return m_data.size();
}

Where m_data is a std::vector<std::string> where each std::string is an individual column in the row. So calling CSVRow::size returns the number of columns.

int main()
{
    std::ifstream file("plop.csv");

    for(CSVIterator loop(file); loop != CSVIterator(); ++loop)
    {
        const auto numCols = (*loop).size();

        std::cout << "Number of Columns: " << numCols << std::endl;

        for(std::size_t i = 0; i < numCols; ++i)
        {
            // Print each column on a new line
            std::cout << (*loop)[i] << std::endl;
        }
    }
}

For input:

cmd, id, addr, qos, len, lock, prot, burst, size, cache, user, duser, dstrb, data

Outputs:

Number of Columns: 14
cmd
 id
 addr
 qos
 len
 lock
 prot
 burst
 size
 cache
 user
 duser
 dstrb
 data
ssell
  • 5,882
  • 2
  • 30
  • 45
  • I added code to your solution to print the columns! See if it makes sense – user2979872 Mar 15 '17 at 20:09
  • @user2979872 You had the gist of it. See my latest revision. – ssell Mar 15 '17 at 20:19
  • @user2979872 Also keep in mind that CSV files use comma delimiters (hence the name Comma Separated Values). So your first column `cmd` does not have the extra space that the subsequent ones do (since the CSV parser only splits on commas). Also I would argue that `row` is a better name than `loop`, but I understand that is the name used in the original answer you reference. – ssell Mar 15 '17 at 20:21
  • Thanks very much. Noted and duly appreciated. – user2979872 Mar 15 '17 at 20:23