srayner
srayner

Reputation: 1837

How do I store a stream of characters in an array?

I have a stream of characters coming over the serial port like this;

FILE1,FILE2,FILE3,

I'm trying to read them in like this;

char* myFiles[20];
boolean done = false;
int fileNum = 0;
int charPos = 0;
char character;
while (!done)
{
  if (Serial.available())
  {
    character = Serial.read();
    if ((character == '\n') || (character == '\r'))
    {
      done = true;
    }
    else if (character == ',')
    {
      myFiles[fileNum][charPos] = '\0';
      fileNum++;
      charPos = 0;
    }
    else
    {
      myFiles[fileNum][charPos] = character;
      charPos++;
    }
  }
}

when I try to print the first value like this;

Serial.println(myFiles[0]);

i get a continuous stream of characters.

What am i doing wrong?

Upvotes: 1

Views: 704

Answers (1)

john
john

Reputation: 87959

What you are doing wrong is not allocating any memory for your strings.

Here's one way to do this

#include <vector>
#include <string>

std::vector<std::string> myFiles;
std::string file;
bool done = false;
char character;
while (!done)
{
  if (Serial.available())
  {
    character = Serial.read();
    if ((character == '\n') || (character == '\r'))
    {
      done = true;
    }
    else if (character == ',')
    {
      myfiles.push_back(file);
      file = "";
    }
    else
    {
      file += character;
    }
  }
}

Serial.println(myFiles[0].c_str());

Since you are programming in C++ you should learn how to use std::vector and std::string, they will save you a lot of grief.

If std::vector and std::string are not available to you (apparently so on Arduino) then the quick hack would be to preallocate a fixed amount of memory for your strings by replacing

char* myFiles[20];

with

char myFiles[20][100];

Upvotes: 4

Related Questions