I am trying to set varaiables from a string using "strtok" and i am having problems getting things set. here is a clip from my code.
response_char = Time 2015 7 2
token = strtok (response_char," ,");
for (int x = 0; x < 10; x++){
if (x == 2) year = atol(token);
else if (x == 3) month = atol(token);
else if (x == 4) day = atol(token);
token = strtok (NULL, " ,");
if (token == NULL) break;
I would like to have it where
year = 2015
month = 7
day = 2
so i can call it back at a later time in the code
Your code fragment is looking for a comma as the separator between fields, when it appears that your are using a space character to delimit fields on the input string. Also, you should check token after the first call to strtok() to make sure it does not return null, which your code likely does. Also, you have a number of syntax errors that need to be cleaned up, too.
See if this works for you:
#define NULL '\0'
void setup() {
char *ptr;
char response_char[] = "2015 7 2"; // Note spaces between fields
Serial.begin(9600);
ptr = strtok (response_char, " "); // Look for spaces between fields
while (ptr != NULL) {
Serial.println(ptr);
ptr = strtok(NULL, " ");
}
}
void loop() {
// put your main code here, to run repeatedly:
}
After you run it, change the input string spaces to commas and the calls to strtok() to see what happens.
ok but how can i set the numbers to what i need them for like;
year == 2015
month == 7
day == 2
i am pulling the time from a clock and i need to store those values to be used in other places
The parse example in serial input basics illustrates the use of strtok()
...R