// SafeString_StringToInt.ino // Converts Arduino String to an int using SafeString.toInt() // https://www.forward.com.au/pfod/ArduinoProgramming/SerialReadingParsing/index.html // // download SafeString library from Arduino library manager // or from the tutorial page // https://www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html // // Pros: Very robust catches invalid numbers and handles leading zeros/white space and trailing white space // Cons: Nothing really, except needs SafeString library to be installed. #include "SafeString.h" cSF(sfString, 15); void setup() { Serial.begin(9600); for (int i = 10; i > 0; i--) { Serial.print(' '); Serial.print(i); delay(500); } Serial.println(); Serial.println(F("SafeString_StringToInt.ino")); sfString = " 0043 \n"; // sfString is a SafeString int result = 0; if (sfString.toInt(result)) { // ignores leading and trailing whitespace Serial.print(F(" result = ")); Serial.println(result); } else { Serial.print(F("Not a valid integer '")); Serial.print(sfString); Serial.println("'"); } // other SafeString conversion methods // toLong(long&) hexToLong(long&) octToLong(long&) binToLong(long&) toFloat(float&) toDouble(double&) // To convert from an Arduino String // first wrap the Arduino String's underlying char[] in a SafeString String numStr = " 0004 \n"; // an Arduino String cSFP(sfStr, (char*)numStr.c_str()); // wrap String's char[] in a SafeString int numResult = 0; if (sfStr.toInt(numResult)) { // ignores leading and trailing whitespace Serial.print(F(" numResult = ")); Serial.println(numResult); } else { Serial.print(F("Not a valid integer '")); Serial.print(numStr); Serial.println("'"); } } void loop() { // put your main code here, to run repeatedly: }