Search code examples
c++arrayscharlibserial

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.


Solution

  • 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; 
    }