-2

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.

Daniel Lara
  • 52
  • 1
  • 7
  • What is `serial_port`? – wally Aug 24 '17 at 20:43
  • [`std::string::push_back`](http://en.cppreference.com/w/cpp/string/basic_string/push_back) would resize as needed. – wally Aug 24 '17 at 20:45
  • In this case, it is receiving a character from a peripheral over serial communication and I am storing it into a variable called character. I am using libserial communication described here: [link]http://libserial.sourceforge.net/tutorial.html#reading-characters [link] – Daniel Lara Aug 24 '17 at 20:46
  • [`std::getline`](http://en.cppreference.com/w/cpp/string/basic_string/getline) might be best. But you would have to replace `char data[256]` with `std::string`. – wally Aug 24 '17 at 20:49

1 Answers1

0

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; 
}
stefan bachert
  • 9,413
  • 4
  • 33
  • 40