// SafeString_firstToken_nextToken_Example.ino for SafeString V4+ // download and install the SafeString library from // www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html #include "SafeString.h" createSafeString(inputLine, 60); // enough space for the input text createSafeString(field, 10); // for the field strings. Should have capacity > largest field length const char delimiters[] = ","; // just comma for delimiter, could also use ",;" if comma or semi-colon seperated fields int nextIdx = 0; // index into inputLine size_t fieldNumber = 0; bool returnEmptyFields = true; // ,, returns an empty field void setup() { // Open serial communications and wait a few seconds Serial.begin(9600); for (int i = 10; i > 0; i--) { Serial.print(' '); Serial.print(i); delay(500); } Serial.println(); //SafeString::setOutput(Serial); // enable full debugging error msgs inputLine = F("23.5, 44a ,, , -5. , +.5, 7a, 33,fred5, 6.5.3, a.5,b.3"); Serial.print(F(" The input is ")); Serial.println(inputLine); nextIdx = 0; // getting tokens start from front of inputLine fieldNumber = 0; // no fields yet Serial.println(); Serial.println(F("Fields with numbers are:-")); } void loop() { // firstToken/nextToken consumes input so this only runs once bool haveToken = inputLine.firstToken(field, ','); // bool haveToken = inputLine.nextToken(field, ',',true,true,true); // firstToken == nextToken with the last (optional) arg set to true while (haveToken) { // still finding tokens field.debug(F(" token => ")); fieldNumber++; float f; if (field.toFloat(f)) { Serial.print(F("Field ")); Serial.print(fieldNumber); Serial.print(F(" : ")); Serial.println(f); } else { SafeString::Output.print(F(" ,")); SafeString::Output.print(field); SafeString::Output.println(F(", is not a number")); } haveToken = inputLine.nextToken(field, ',', true); // skips empty fields by default, use optional arg (true) to return empty fields } // rest of sketch runs here after each token found }