Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
10 years, 4 months ago.
How can I change string object to char array?
Hello
I am working on a program to parse a serial data. I found a program that accepts the serial data in string object type and I want to parse that data with funcing - "strtok" but it accepts only char array format. I tried to change string data to char array but my poor knowledge of C++ could not help. Please help me. Thank you! The prom is as below:
#include "mbed.h"
#include <string>
Serial pc(USBTX, USBRX);
string b;
//char s = ",";// for deliminator
char *token; // For fetching token one after another
void callback() {
}
int main() {
// pc.attach(&callback);
//buffer variables
char lezen;
//if data is ready in the buffer
while (1) {
//read 1 character
lezen = pc.getc();
//if character is $ than it is the start of a sentence
if (lezen == '$') {
//so the pointer should be set to the first position
b.clear();
}
//write buffer character to big buffer string
b += lezen;
//if the character is # than the end of the sentence is reached and some stuff has to be done
if (lezen == '#') {
b.erase(0,1);
b.erase(b.length()-1,1);
token = strtok(b, ","); ///*****It does not work here*************
//Get the rest
while( token != NULL )
{
printf( " %s\n", token );
token = strtok(NULL, ",");
}
}
}
}
I show the part that is not working with asterisk *.
I just want to parse the serial data sent like ( S1,200) into ... .like .. command = S1; parameter = 200
If there is any other better solution .. Please let me know.
Thank you for your support.
sincerely princekham
1 Answer
10 years, 4 months ago.
The short answer is strtok(b.c_str(), ",");
std::stringc_str() returns a char* to a c style string with the same contents as the c++ string.
However it would probably be easiest to avoid c++ strings completely and use a c style char array.
#define maxInLen 64
main () {
...
char inBuffer[maxInLen];
int inCount = 0;
bool startDetected = false;
while (1) {
inBuffer[inCount] = pc.getc();
//if character is $ than it is the start of a sentence
if (inBuffer[inCount] == '$') {
startDetected = true;
} else if (startDetected) {
//if the character is # than the end of the sentence is reached and some stuff has to be done
if (inBuffer[inCount]== '#') {
inBuffer[inCount] = 0; // change the # to a null so that the string is null terminated.
token = strtok(inBuffer, ",");
//Get the rest
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, ",");
}
startDetected = false;
inCount = 0;
} else { // not the end of a line
inCount++;
if (inCount == maxInLen) {
pc.puts("Buffer overflow");
inCount = 0;
startDetected = false;
}
}
} // end of if start char seen
} // while loop
}