Daniel Lara
Daniel Lara

Reputation: 52

C++ store consecutive chars into an array

This could be a very trivial question, but I have been searching how to get around it without much luck. I have a function to read from the serial port using the libserial function, the response I will get always finishes with a carriage return or a "\r" so, in order to read it, I was thinking in reading character by character comparing if it is not a \r and then storing each character into an array for later usage. My function is as follows:

void serial_read()
{
char character;
int numCharacter = 0;
char data[256];

     while(character != '\r')
     { 
         serial_port >> character; 
         numCharacter++;
         character >> data[numCharacter];
     }
cout << data; 
}

In summary, probably my question should be how to store consecutive chars into an array. Thank you very much for your valuable insight.

Upvotes: -2

Views: 208

Answers (1)

stefan bachert
stefan bachert

Reputation: 9626

I guess you intended

void serial_read()
{
  char character = 0;
  int numCharacter = 0;
  char data[256];

  while(character != '\r' && numCharacter < 255)
  { 
     serial_port >> character; 
     data [numCharacter ++] = character;
  }
  data [numCharacter] = 0;  // close "string" 
  cout << data; 
}

Upvotes: 0

Related Questions