Determine number of items in csv file by arduino

Dear all,
Im struggling with the following:

I need to determine the number of items per line in a csv file.
The arduino is reading a csv file from an sdcard.
The csv file is semicolon separated, (:wink:
Before i can work with the values from a record ( gathered via parseint() its imperatie to know how many values there are in a record (one line)

The csv file can be updated once and a while, and that should not result in update the sketch in the arduino.

Therefore i need a piece of as simple as possible code to read the number of values per record during setup.
There should be a smart trick to count the number of semicolums in a line for instance

Please help!

Kind regards

Sjors

Start a count at 0; scan the line character by character, each time add 1 to the count; stop when you reach end of line. Maybe not smart but obvious.

Do you mean something like this ?

void setup()
{
  Serial.begin(115200);
  Serial.println(countItems("1;2;3;4;5;6;"));
  Serial.println(countItems("Mary;had;a;little;lamb"));
}

void loop()
{
}

byte countItems(char * line)
{
  Serial.println(line);
  byte count = 0;
  for (int c = 0; c < strlen(line); c++)
  {
    if (line[c] == ';')
    {
      count++;
    }
  }
  return count;
}

Remember there's one more value after the last semicolon, so you should initialize count to 1.

As usual the Devil is in the detail. For instance we don't know whether the data will always end in a semicolon, never end in a semicolon or will sometimes end in a semicolon

Good point. It would, of course, help to know the exact format of the data such as whether it always ends in a semicolon, never ends in a semicolon or sometimes ends in a semicolon

Meanwhile, consider this revised version of the code

void setup()
{
  Serial.begin(115200);
  Serial.println(countItems("1;2;3;4;5;6;"));
  Serial.println(countItems("Mary;had;a;little;lamb"));
  Serial.println(countItems(""));
}

void loop()
{
}

byte countItems(char * line)
{
  Serial.println(line);
  if (strlen(line) == 0)
  {
    return 0;
  }
  byte count = 1;
  for (int c = 0; c < strlen(line); c++)
  {
    if (line[c] == ';')
    {
      count++;
    }
  }
  if (line[strlen(line) - 1] == ';') // ends with a semicolon
  {
    count--;;
  }
  return count;
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.